Ad

Filter Array Using A Second Array In Javascript

- 1 answer

I have a simple javascript array:

var earningarray = [
  ["2015-12-29T23:59:59+00:00", 3],
  ["2015-12-28T23:59:59+00:00", 3]
];

I have another array.

var paddingarray = [
  ["2015-12-19T23:59:59+00:00", 0],
  ["2015-12-20T23:59:59+00:00", 0],
  ["2015-12-21T23:59:59+00:00", 0],
  ["2015-12-22T23:59:59+00:00", 0],
  ["2015-12-23T23:59:59+00:00", 0],
  ["2015-12-24T23:59:59+00:00", 0],
  ["2015-12-25T23:59:59+00:00", 0],
  ["2015-12-26T23:59:59+00:00", 0],
  ["2015-12-27T23:59:59+00:00", 0],
  ["2015-12-28T23:59:59+00:00", 0]
];

What I am trying to achieve is to remove from paddingarray the rows where they exist in earningsarray based on the datestamp (first column).

I have tried doing it with this function:

newarray = paddingarray.filter(function(val) {
  return earningarray[0].indexOf(val[0]) == -1;
});

However it does not filter the array correctly and outputs exactly the same as the original paddingarray. Any ideas?

Ad

Answer

Try using Array.prototype.some()

var earningarray = [
  ["2015-12-29T23:59:59+00:00", 3],
  ["2015-12-28T23:59:59+00:00", 3]
];

var paddingarray = [
  ["2015-12-19T23:59:59+00:00", 0],
  ["2015-12-20T23:59:59+00:00", 0],
  ["2015-12-21T23:59:59+00:00", 0],
  ["2015-12-22T23:59:59+00:00", 0],
  ["2015-12-23T23:59:59+00:00", 0],
  ["2015-12-24T23:59:59+00:00", 0],
  ["2015-12-25T23:59:59+00:00", 0],
  ["2015-12-26T23:59:59+00:00", 0],
  ["2015-12-27T23:59:59+00:00", 0],
  ["2015-12-28T23:59:59+00:00", 0]
];

var newarray = paddingarray.filter(function(val) {
  return !earningarray.some(function(v) {
    return v[0] === val[0]
  })
});

console.log(paddingarray.length, newarray.length)

Ad
source: stackoverflow.com
Ad