Jamie Jordan
Jamie Jordan

Reputation: 251

using javascript filter() with a flag

I want to return arr2 but want to prompt the user whether there's changes or not by comparing it with arr. with below's approach, I got id of undefined if arr2 have any missing item.

var arr = [{
  id: 1,
  name: 'something'
}, {
  id: 2,
  name: 'something2'
}]

var arr2 = [{
  id: 1,
  name: 'something'
}]

var result = arr.filter(function(obj, i) {
  return obj.id == arr2[i].id;
});

document.write(JSON.stringify(result))

Upvotes: 1

Views: 351

Answers (2)

Pranav C Balan
Pranav C Balan

Reputation: 115202

The problem in your code is that arr[1] is undefined and you are trying to get id property of undefined. Now what you can do is, get id's in array then get index and check based on that in filter.

var arr = [{
  id: 1,
  name: 'something'
}, {
  id: 2,
  name: 'something2'
}]

var arr2 = [{
  id: 1,
  name: 'something'
}];

var arrIds = arr2.map(function(v) {
  return v.id;
});

var result = arr.filter(function(obj) {
  var i = arrIds.indexOf(obj.id);
  return i > -1 &&
    obj.name == arr2[i].name; // check name property here
});

document.write(JSON.stringify(result))

Upvotes: 1

Rayon
Rayon

Reputation: 36609

Loop through arr2 in a callback of the .filter to test each item of arr2.

var arr = [{
  id: 1,
  name: 'something'
}, {
  id: 2,
  name: 'something2'
}]

var arr2 = [{
  id: 1,
  name: 'something'
}, {
  id: 5,
  name: 'something'
}, {
  id: 8,
  name: 'something'
}];

var isValInArr = function(arr, key, val) {
  for (var i = 0, len = arr.length; i < len; i++) {
    if (arr[i][key] === val) {
      return true;
    }
  }
  return false;
};

var result = arr.filter(function(obj, i) {
  return isValInArr(arr2, 'id', obj.id);
});

document.write(JSON.stringify(result))

Upvotes: 0

Related Questions