Skip to content Skip to sidebar Skip to footer

Filtering Arrays Of Complex Objects With Loops

I have two arrays of complex nexted objects that I'm looking for qualifying values within using loops and if statements as seen below. When I find a qualifying object, I need to f

Solution 1:

There are a few things wrong with your code, but the reason why you think that push isn't working is because you are overriding your array2 inside the loop.

The push never gets called because your for loop sees an empty array2 when you are doing var array2 = _.without(array2, emptyArray);

Basically var array2 = _.without(array2 /* this is empty, you just overrode it in this scope */, emptyArray); will always result in an empty array and your for loop will exit because length is array2.length === 0 from the start.

Also, you want to use _.difference instead of _.without

var array = [1, 2, 3, 4, 1, 2, 3, 4];
var array2 = [2, 4, 6, 8, 10];
var emptyArray = [];

for (var i = 0; i < array.length; i++) {
  var something = array[i];
  array2 = _.difference(array2, emptyArray);
  for (var j = 0; j < array2.length; j++) {
    var value = array2[j];
    if (something === value) {
      emptyArray.push(value);
      break;
    }
  }
}

console.log("array2",array2);
console.log("emptyArray", emptyArray);
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.5.0/lodash.js"></script>
array2 [6, 8, 10]
emptyArray [2, 4]

Solution 2:

vararray = [1, 2, 3, 4, 1, 2, 3, 4];
var array2 = [2, 4, 6, 8, 10];
var emptyArray = [];

for (var i = 0; i < array.length; i++) {
  var something = array[i];
  for (var j = 0; j < array2.length; j++) {
    var value = array2[j];
    if (something === value) {
      array2 = _.without(array2, value);
      break;
    }
  }
}

Post a Comment for "Filtering Arrays Of Complex Objects With Loops"