1

Simple question, but I can´t get over it...

I have two arrays:

var arrayA = [67.98, "-", 91.77, "-", "-", 8.09];
var arrayB = [3, 4, 9, 1, 12, 77];

So, I need to remove all values from arrayB which have the indexes of the value "-" in arrayA. In this case the result of arrayB should be:

arrayB = [3, 9, 77]

Many thanks.

Jaybruh
  • 333
  • 5
  • 14

2 Answers2

7

Use Array.filter() on arrayB, and preserve items that their respective item in arrayA is not a dash:

var arrayA = [67.98, "-", 91.77, "-", "-", 8.09];
var arrayB = [3, 4, 9, 1, 12, 77];

var result = arrayB.filter(function(_, i) {
  return arrayA[i] !== '-';
});

console.log(result);
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
  • Works perfect. I first tried an approach with a for loop, likewise to the comment below, but I think this is much easier, thanks! – Jaybruh Mar 19 '18 at 12:53
1

    var arrayA = [67.98, "-", 91.77, "-", "-", 8.09];
    var arrayB = [3, 4, 9, 1, 12, 77];
    
    for (var i = arrayB.length - 1; i >= 0; i--) {
        if (arrayA[i] == "-") { 
            arrayB.splice(i, 1);
        }
    }
    
    console.log(arrayB);

See: Looping through array and removing items, without breaking for loop

GhitaB
  • 3,275
  • 3
  • 33
  • 62