1

I'm using knockout and have two arrays.

I want to find the difference between the arrays, i.e. any items that are in the longer array that are not in the smaller one.

i have

    console.warn(items1); // 10
    console.warn(items2); // 11

    var filtered = ko.utils.arrayFilter(items1, function (e) {
        return !items2.indexOf(e) > -1;
    });

    console.warn(filtered); // 10

How do I changes this to leave filtered with the 1 new item?

I've tried return items2.indexOf(e) > -1;

I've tried switching the arrays around on the filter and return.

I've tried return items2.indexOf(e) == -1;

All either give 10, 11, or 0.

How do I make it return 1?

Sven.hig
  • 4,449
  • 2
  • 8
  • 18
  • 1
    Does this answer your question? [How to get the difference between two arrays in JavaScript?](https://stackoverflow.com/questions/1187518/how-to-get-the-difference-between-two-arrays-in-javascript) – Matt Jul 02 '20 at 16:38

3 Answers3

1

You can get the difference by filtering the 2nd array for items that are not included in the first.

const difference = items2.filter(item => !items1.includes(item));

Matt
  • 5,315
  • 1
  • 30
  • 57
0

You can use filter to check for the difference for example

ar1=[1,2,3,4,5,7,8]
ar2=[2,10,9,1,2,3,4,5,7]

dif=ar2.filter(x=>!ar1.some(y=>x==y))
console.log(dif)
// or
dif=ar2.filter(x=>!ar1.includes(x))
console.log(dif)
Sven.hig
  • 4,449
  • 2
  • 8
  • 18
0

I would suggest using !includes as per the other answers, but for the sake of completeness this is how you would keep your approach if you want to:

var filtered = ko.utils.arrayFilter(items2, function (e) {
    return !items1.indexOf(e) === -1;
});

ko.utils.arrayFilter will return items from the array you pass in as the first argument, and you want items from the longer array, so you should pass in items2. You want it to return items which are not in items1, so indexOf will return -1 for those items.

Tim
  • 5,435
  • 7
  • 42
  • 62
  • 1
    This is the correct answer, but in the end I used _.differenceBy(items2, items1, 'Id'); as my arrays were of objects and Id was needed. This seems to work a treat, but your answer was correct for what I asked –  Jul 02 '20 at 17:22