0

I have this array

var bmpArrayNames=["strip_cropping", "crop_rotation", "cover_crops", "filter_strips", "grassed_waterway", "conservation_tillage", "binary_wetlands"];

and this array

var bmpArray=["1", "1", "0", "0", "0", "0", "0"];

I need to loop through this bmpArray looking to see if the value =1. If it does, I want to replace the value with the value at the same index of the bmpArrayNames. Then I would remove all "0" ultimately ending with bmpArray=["strip_cropping,"crop_rotation"]

I started with this but am not stuck

$.each(bmpArray, function(index, value) { 
if (value=="1")
//so if i find a match how do I replace with the same indexed value in the other array.

Thanks in advance!

3 Answers 3

2

Try:

$.each(bmpArray, function(index, value) {
    if (value == "1") {
        bmpArray[index] = bmpArrayNames[index];
    }
});

$.grep(bmpArray, function(item, index) {
    return bmpArray[index] != "0";
});

Input:

var bmpArrayNames = ["strip_cropping", 
                     "crop_rotation", 
                     "cover_crops",
                     "filter_strips", 
                     "grassed_waterway", 
                     "conservation_tillage", 
                     "binary_wetlands"];

var bmpArray = ["1", "1", "0", "0", "0", "0", "0"];

Output:

bmpArray : ["strip_cropping", "crop_rotation"];
Sign up to request clarification or add additional context in comments.

1 Comment

thanks for the easy solution! I was making more out of it then I needed to!
2

This will update the bmpArray:

$.each(bmpArray, function(index, value) { 
    if (value==="1"){
        bmpArray[index] = bmpArrayNames[index];
    }
});

Note that use of the triple equals operator is encouraged, to prevent unintended type coersion.

To remove the zeroes you can use the grepfunction, like so:

bmpArray = $.grep(bmpArray, function(item){
    return item !== "0";
});

Comments

2

if its that you want:

["strip_cropping", "crop_rotation"]

as a final result you could use jQuery .grep method:

var bmpArrayNames = ["strip_cropping", "crop_rotation", "cover_crops", "filter_strips", "grassed_waterway", "conservation_tillage", "binary_wetlands"];
var bmpArray = ["1", "1", "0", "0", "0", "0", "0"];

bmpArrayNames = jQuery.grep( bmpArrayNames, function(item, index) {
    return bmpArray[index] == "1";
});

bmpArrayNames will now be ["strip_cropping", "crop_rotation"]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.