jeynon
jeynon

Reputation: 322

if statement in jQuery each. loop of array

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!

Upvotes: 0

Views: 4589

Answers (3)

Daniel Li
Daniel Li

Reputation: 15379

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"];

Upvotes: 2

voigtan
voigtan

Reputation: 9031

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"]

Upvotes: 2

codebox
codebox

Reputation: 20254

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";
});

Upvotes: 2

Related Questions