Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get value not in array

Given two arrays: (one and two).

one: contains values

two: contains objects with values

I need to get the values from one which are not in two. I've tried with .filter() and .indexOf() but don't get the desired result.

In the following case I expect result to have the value 333. How to achieve that?

var one = [111, 222, 333, 444];
var two = [
  { identifier: 111 },
  { identifier: 222 },
  { identifier: 444 }
];

var result = two.filter(function (item) {
    console.log(item.identifier, one.indexOf(item.identifier));
});

console.log('result: ', result);
like image 263
caramba Avatar asked Feb 12 '26 22:02

caramba


1 Answers

Just do what you want, filter one and take only those which are not in two (find it in two, if found it will return the object i.e. true equivalent if not found then it will return undefined i.e. false equivalent and negate ! it)

var one = [111, 222, 333, 444];
var two = [
  { identifier: 111 },
  { identifier: 222 },
  { identifier: 444 }
];
var resultArr = one.filter(function(val){
    return !two.find(function(obj){
        return val===obj.identifier;
    });
});

console.log(resultArr)
like image 156
Koushik Chatterjee Avatar answered Feb 15 '26 11:02

Koushik Chatterjee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!