Reputation: 35
I have some js arrays. For example:
var array1 ="Apple","Orange","Lemon";
var array2 ="Shop1","Shop2","Shop3";
var array3 ="1","NA","4";
var finalArray=[];
finalArray.push(array1,array2,array3);
The items in each array are linked as I am using them to generate a chart. However, how can remove linked items from finalArray so that if array3 contains 'NA' then each linked item is removed from finalArray. Thus finalArray would contain:
array1 ="Apple","Orange";
array2 ="Shop1","Shop3";
array3 ="1","4";
Any help or pointers in the right direction is appreciated.
Upvotes: 0
Views: 55
Reputation: 386736
You could iterate the array with the flags from the end and splice all arrays of finalArray
.
var array1 = ["Apple", "Orange", "Lemon"],
array2 = ["Shop1", "Shop2", "Shop3"],
array3 = ["1", "NA", "4"],
finalArray = [array1, array2, array3],
i = array3.length;
while (i--) {
if (array3[i] !== 'NA') continue;
finalArray.forEach(a => a.splice(i, 1));
}
console.log(finalArray);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 0
Reputation: 37755
You can use reduce
Here idea is
NA
or not.NA
push the values to respective keys.NA
just simply return op without any change.var array1 =["Apple","Orange","Lemon"];
var array2 =["Shop1","Shop2","Shop3"];
var array3 =["1","NA","4"];
var finalArray = array3.reduce((op,inp,index) => {
if( inp != 'NA') {
op.array1.push(array1[index])
op.array2.push(array2[index])
op.array3.push(inp)
}
return op
},{array1:[], array2:[], array3:[]})
console.log(finalArray)
Upvotes: 1