Как найти пересечение двух массивов js

Время на прочтение
5 мин

Количество просмотров 45K

Массивы являются одной из самых популярных структур данных в JavaScript, потому что они используются для хранения данных. Кроме этого, массивы дают много возможностей для работы с этими самыми данными. Понимая, что для тех, кто находится в начале пути изучения JavaScript, массивы являются одной из самых основных тем, в этой статье я хотел бы познакомить вас с некоторыми полезными трюками, о которых вы могли не знать. Давайте начнем.

1. Как в массиве оставить только уникальные значения

Это очень популярный вопрос во время интервью на позицию Javascript-разработчика. Вот быстрое и простое решение этой задачки. Для начала вам нужно получить уникальные значения массива, для этого можно использовать new Set() (прим. перев.: структура данных Set хранит только уникальные значения). Далее нужно преобразовать структуру данных Set в массив. Я хочу познакомить вас с двумя способами, как это можно сделать: первый – с помощью метода from(), второй – с помощью оператора spread ("…").

const fruits = ['banana', 'apple', 'orange', 'watermelon', 'apple', 'orange', 'grape', 'apple'];

// Первый метод
const uniqueFruits = Array.from(new Set(fruits));
console.log(uniqueFruits); // вернет ['banana', 'apple', 'orange', 'watermelon', 'grape']

// Второй метод
const uniqueFruits2 = [...new Set(fruits)];
console.log(uniqueFruits2); // вернет ['banana', 'apple', 'orange', 'watermelon', 'grape']

Легко, правда?

2. Как заменить значения в массиве

Бывают такие ситуации, когда нужно заменить значения в массиве другими значениями. Для этого существует хороший метод, о котором вы, возможно, не знали – метод splice(start, value to remove, values to add), где start – номер индекса, начиная с которого мы хотим удалить элементы массива, value to remove – число элементов, которые мы хотим удалить, а values to add – элементы, которые мы хотим вставить на место удаленных:

const fruits = ['banana', 'apple', 'orange', 'watermelon', 'apple', 'orange', 'grape', 'apple'];
fruits.splice(0, 2, 'potato', 'tomato');
console.log(fruits); // вернет ["potato", "tomato", "orange", "watermelon", "apple", "orange", "grape", "apple"]

3. Как трансформировать массив, не используя метод map()

Наверное, все знают метод массива map(), но есть и другое решение, которое может быть использовано для получения аналогичного эффекта и чистого кода. Для этого мы можем воспользоваться методом from():

const friends = [
    { name: 'John', age: 22 },
    { name: 'Peter', age: 23 },
    { name: 'Mark', age: 24 },
    { name: 'Maria', age: 22 },
    { name: 'Monica', age: 21 },
    { name: 'Martha', age: 19 },
]

const friendsNames = Array.from(friends, ({name}) => name);
console.log(friendsNames); // вернет ['John', 'Peter', 'Mark', 'Maria', 'Monica', 'Martha']

4. Как быстро очистить массив

Например, у нас есть массив, в котором много элементов. Нам нужно его очистить (неважно для какой цели), при этом мы не хотим удалять элементы один за другим. Это очень просто сделать одной строчкой кода. Чтобы очистить массив, нам нужно установить длину массива в 0, и всё!

const fruits = ['banana', 'apple', 'orange', 'watermelon', 'apple', 'orange', 'grape', 'apple'];
fruits.length = 0;
console.log(fruits); // вернет []

5. Как преобразовать массив в объект

Бывает такая ситуация: у нас есть массив, но нам нужен объект (опять неважно для какой цели) с этими данными, и самый быстрый способ преобразовать массив в объект – это использовать оператор spread ("..."):

const fruits = ['banana', 'apple', 'orange', 'watermelon', 'apple', 'orange', 'grape', 'apple'];
const fruitsObj = { ...fruits };
console.log(fruitsObj); // вернет {0: 'banana', 1: 'apple', 2: 'orange', 3: 'watermelon', 4: 'apple', 5: 'orange', 6: 'grape', 7: 'apple'}

6. Как заполнить массив одинаковыми значениями

Бывают разные ситуации, когда мы хотим создать массив и заполнить его некоторыми значениями, или нам нужен массив с одинаковыми значениями. Метод fill() для подобных задач является отличным решением:

const newArray = new Array(10).fill('1');
console.log(newArray); // вернет ["1", "1", "1", "1", "1", "1", "1", "1", "1", "1"]

7. Как объединить более двух массивов

Вы знаете, как объединить массивы в один, не используя метод concat()? Существует простой способ объединить любое количество массивов в один массив одной строчкой кода. Как вы, вероятно, уже поняли, оператор spread ("...") является довольно полезным инструментом при работе с массивами, как и в этом случае:

const fruits = ['apple', 'banana', 'orange'];
const meat = ['poultry', 'beef', 'fish'];
const vegetables = ['potato', 'tomato', 'cucumber'];
const food = [...fruits, ...meat, ...vegetables];
console.log(food); // вернет ["apple", "banana", "orange", "poultry", "beef", "fish", "potato", "tomato", "cucumber"]

8. Как найти пересечение двух массивов

С этой задачей вы можете столкнуться на любом JavaScript-собеседовании, потому что ее решение показывает ваши знания методов массива, а также то, как вы мыслите. Чтобы найти общие значения двух массивов, мы будем использовать один из ранее рассмотренных методов в этой статье, чтобы убедиться, что значения в массиве, который мы проверяем, не дублируются. Кроме этого, мы воспользуемся методами filter() и includes(). В результате мы получим массив с элементами, которые представлены в обоих массивах:

const numOne = [0, 2, 4, 6, 8, 8];
const numTwo = [1, 2, 3, 4, 5, 6];
const duplicatedValues = [...new Set(numOne)].filter(item => numTwo.includes(item));
console.log(duplicatedValues); // вернет [2, 4, 6]

9. Как удалить ложные значения из массива

Для начала, давайте определим ложные значения. В Javascript ложными значениями являются: false, 0, «», null, NaN и undefined. Теперь мы можем выяснить, как удалить такие значения из нашего массива. Для достижения этой цели нам потребуется метод filter():

const mixedArr = [0, 'blue', '', NaN, 9, true, undefined, 'white', false];
const trueArr = mixedArr.filter(Boolean);
console.log(trueArr); // вернет ["blue", 9, true, "white"]

10. Как получить рандомное значение массива

Иногда нам нужно выбрать рандомное значение массива. Чтобы решение было простым, коротким и быстрым, мы можем получить случайный номер индекса в соответствии с длиной массива. Посмотрите на этот пример:

const colors = ['blue', 'white', 'green', 'navy', 'pink', 'purple', 'orange', 'yellow', 'black', 'brown'];
const randomColor = colors[(Math.floor(Math.random() * (colors.length)))];
console.log(randomColor); // вернет рандомный цвет из массива

11. Как развернуть массив в обратную сторону

Когда нам нужно «перевернуть» наш массив, нет необходимости создавать его через сложные циклы и функции, потому что есть простой метод массива reverse(), который делает все это за нас, и одной строчкой кода мы можем «перевернуть» наш массив:

const colors = ['blue', 'white', 'green', 'navy', 'pink', 'purple', 'orange', 'yellow', 'black', 'brown'];
const reversedColors = colors.reverse();
console.log(reversedColors); // вернет ["brown", "black", "yellow", "orange", "purple", "pink", "navy", "green", "white", "blue"]

12. Метод lastIndexOf()

В JavaScript есть интересный метод lastIndexOf(elem), который позволяет найти индекс последнего вхождения элемента elem. Например, если наш массив имеет дублированные значения, мы можем найти позицию последнего вхождения в него. Взгляните на следующий пример кода:

const nums = [1, 5, 2, 6, 3, 5, 2, 3, 6, 5, 2, 7];
const lastIndex = nums.lastIndexOf(5);
console.log(lastIndex); // вернет 9

13. Как просуммировать все значения в массиве

Еще один популярный вопрос во время собеседования на позицию JavaScript-разработчика. Сумму всех элементов можно найти одной строчкой кода, если знать метод reduce():

const nums = [1, 5, 2, 6];
const sum = nums.reduce((x, y) => x + y);
console.log(sum); // вернет 14

Заключение

В этой статье я познакомил вас с 13 полезными приёмами, которые помогут вам писать чистый и краткий код. Кроме этого, не забывайте, что есть много различных трюков, которые вы можете использовать в Javascript и которые стоит изучить не только для работы с массивами, но и для других структур данных. Я надеюсь, что вам понравились решения, представленные в статье, и вы будете использовать их для улучшения процесса разработки.

Приятного написания кода!

Шпаргалка для работы с массивами в JavaScript ES6+.

seapp88

Пересечение даст нам элементы, которые объединяют оба массива, в этом случае результат должен быть [1,5].

let intersection = arrA.filter(x => arrB.includes(x));

Разность будет выводить элементы из массива A, которых нет в массиве B. Результат будет [3,4].

let difference = arrA.filter(x => !arrB.includes(x));

В этом случае вы получите массив, содержащий все элементы arrA, которых нет в arrB, и наоборот, так что результат должен быть [2,3,4,6,7].

let difference = arrA.filter(x => !arrB.includes(x)).concat(arrB.filter(x => !arrA.includes(x)));

​ seapp88

Объединение должно быть самым простым из них всех, в конце концов, результатом должны быть все элементы из A, все из B или оба, как это [1,2,3,4,5,6,7].

let union = […arrA, …arrB];

Но есть проблема в том, что мы получим дублированные элементы, так что теоретически это не объединение. Для этого мы можем использовать new Set():

let union = […new Set([…arrA, …arrB)];

В этом посте мы обсудим, как найти пересечение двух массивов в JavaScript. По порядку слов перечислите общие значения, присутствующие в каждом из массивов.

Например, пересечение массивов [1,2,3,4] а также [3,4,5] является [3,4].

1. Использование Array.prototype.filter() функция

Идея состоит в том, чтобы проверить наличие каждого элемента первого массива во втором массиве. Это можно легко сделать с помощью indexOf() метод с filter() метод следующим образом:

var first = [ 1, 2, 3 ];

var second = [ 2, 3, 4, 5 ];

var common = first.filter(x => second.indexOf(x) !== 1)

console.log(«The common elements are: « + common);

/*

    результат: The common elements are: 2,3

*/

Скачать  Выполнить код

 
Для проверки наличия определенного элемента в массиве также можно использовать последнюю includes() метод, который возвращает логическое значение. Это показано ниже:

var first = [ 1, 2, 3 ];

var second = [ 2, 3, 4, 5 ];

var common = first.filter(x => second.includes(x))

console.log(«The common elements are: « + common);

/*

    результат: The common elements are: 2,3

*/

Скачать  Выполнить код

 
Обратите внимание, что это решение не приводит к уникальным значениям на выходе.

2. Использование набора

Другим решением является преобразование массива в ES6. Set и назовите его has() метод для проверки других элементов массива.

function intersection(first, second)

{

    var s = new Set(second);

    return first.filter(item => s.has(item));

};

var first = [ 1, 2, 3 ];

var second = [ 2, 3, 4, 5 ];

var common = intersection(first, second);

console.log(«The common elements are: « + common);

/*

    результат: The common elements are: 2,3

*/

Скачать  Выполнить код

 
Чтобы не печатать дубликаты в выводе, вы можете удалить повторяющиеся элементы из первого массива, как показано ниже:

function intersection(first, second)

{

    first = new Set(first);

    second = new Set(second);

    return [...first].filter(item => second.has(item));

}

var first = [ 1, 2, 3 ];

var second = [ 2, 3, 4, 5 ];

var common = intersection(first, second);

console.log(«Common elements are: « + common);

/*

    результат: Common elements are: 2,3

*/

Скачать  Выполнить код

3. Использование библиотеки Lodash/Underscore

Если вы не хотите использовать Set в качестве промежуточной структуры данных для поиска общих значений, код можно упростить, используя подчеркивание или библиотеку lodash. В следующем примере кода выводятся уникальные значения, присутствующие в заданных массивах, с использованием intersection() метод.

var _ = require(‘lodash’);        // или подчеркивание

var first = [ 1, 2, 3 ];

var second = [ 2, 3, 4, 5 ];

var common = _.intersection(first, second);

console.log(«The common elements are: « + common);

/*

    результат: The common elements are: 2,3

*/

Скачать код

4. Использование jQuery

С jQuery вы можете использовать следующий код:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

const { JSDOM } = require(«jsdom»);

const { window } = new JSDOM();

var $ = require(«jquery»)(window);

var first = [ 1, 2, 3 ];

var second = [ 2, 3, 4, 5 ];

var secondNotFirst = $(second).not(first);    // [ 2, 3, 4, 5 ] — [ 1, 2, 3 ] = [4,5]

var common = $(second).not(secondNotFirst);    // [ 2, 3, 4, 5 ] — [4,5]    = [2,3]

console.log(«The common elements are:»);

for (var i = 0; i < common.length; i++) {

    console.log(common[i]);

}

/*

    результат: The common elements are:

    2

    3

*/

Скачать код

 
Код можно упростить с помощью jQuery. filter() метод:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

const { JSDOM } = require(«jsdom»);

const { window } = new JSDOM();

var $ = require(«jquery»)(window);

var first = [ 1, 2, 3 ];

var second = [ 2, 3, 4, 5 ];

var common = $(second).filter(first);

console.log(«The common elements are:»);

for (var i = 0; i < common.length; i++) {

    console.log(common[i]);

}

/*

    результат: The common elements are:

    2

    3

*/

Скачать код

Вот и все, что нужно для поиска пересечения двух массивов в JavaScript.

Another indexed approach able to process any number of arrays at once:

// Calculate intersection of multiple array or object values.
function intersect (arrList) {
    var arrLength = Object.keys(arrList).length;
        // (Also accepts regular objects as input)
    var index = {};
    for (var i in arrList) {
        for (var j in arrList[i]) {
            var v = arrList[i][j];
            if (index[v] === undefined) index[v] = 0;
            index[v]++;
        };
    };
    var retv = [];
    for (var i in index) {
        if (index[i] == arrLength) retv.push(i);
    };
    return retv;
};

It works only for values that can be evaluated as strings and you should pass them as an array like:

intersect ([arr1, arr2, arr3...]);

…but it transparently accepts objects as parameter or as any of the elements to be intersected (always returning array of common values). Examples:

intersect ({foo: [1, 2, 3, 4], bar: {a: 2, j:4}}); // [2, 4]
intersect ([{x: "hello", y: "world"}, ["hello", "user"]]); // ["hello"]

EDIT: I just noticed that this is, in a way, slightly buggy.

That is: I coded it thinking that input arrays cannot itself contain repetitions (as provided example doesn’t).

But if input arrays happen to contain repetitions, that would produce wrong results. Example (using below implementation):

intersect ([[1, 3, 4, 6, 3], [1, 8, 99]]);
// Expected: [ '1' ]
// Actual: [ '1', '3' ]

Fortunately this is easy to fix by simply adding second level indexing. That is:

Change:

        if (index[v] === undefined) index[v] = 0;
        index[v]++;

by:

        if (index[v] === undefined) index[v] = {};
        index[v][i] = true; // Mark as present in i input.

…and:

         if (index[i] == arrLength) retv.push(i);

by:

         if (Object.keys(index[i]).length == arrLength) retv.push(i);

Complete example:

// Calculate intersection of multiple array or object values.
function intersect (arrList) {
    var arrLength = Object.keys(arrList).length;
        // (Also accepts regular objects as input)
    var index = {};
    for (var i in arrList) {
        for (var j in arrList[i]) {
            var v = arrList[i][j];
            if (index[v] === undefined) index[v] = {};
            index[v][i] = true; // Mark as present in i input.
        };
    };
    var retv = [];
    for (var i in index) {
        if (Object.keys(index[i]).length == arrLength) retv.push(i);
    };
    return retv;
};

intersect ([[1, 3, 4, 6, 3], [1, 8, 99]]); // [ '1' ]

I have two arrays list1 and list2 which have objects with some properties; userId is the Id or unique property:

list1 = [
    { userId: 1234, userName: 'XYZ'  }, 
    { userId: 1235, userName: 'ABC'  }, 
    { userId: 1236, userName: 'IJKL' },
    { userId: 1237, userName: 'WXYZ' }, 
    { userId: 1238, userName: 'LMNO' }
]

list2 = [
    { userId: 1235, userName: 'ABC'  },  
    { userId: 1236, userName: 'IJKL' },
    { userId: 1252, userName: 'AAAA' }
]

I’m looking for an easy way to execute the following three operations:

  1. list1 operation list2 should return the intersection of elements:

    [
        { userId: 1235, userName: 'ABC'  },
        { userId: 1236, userName: 'IJKL' }
    ]
    
  2. list1 operation list2 should return the list of all elements from list1 which don’t occur in list2:

    [
        { userId: 1234, userName: 'XYZ'  },
        { userId: 1237, userName: 'WXYZ' }, 
        { userId: 1238, userName: 'LMNO' }
    ]
    
  3. list2 operation list1 should return the list of elements from list2 which don’t occur in list1:

    [
        { userId: 1252, userName: 'AAAA' }
    ]
    

trincot's user avatar

trincot

308k35 gold badges240 silver badges282 bronze badges

asked Oct 26, 2015 at 22:08

Shashi's user avatar

3

You could define three functions inBoth, inFirstOnly, and inSecondOnly which all take two lists as arguments, and return a list as can be understood from the function name. The main logic could be put in a common function operation that all three rely on.

Here are a few implementations for that operation to choose from, for which you can find a snippet further down:

  • Plain old JavaScript for loops
  • Arrow functions using filter and some array methods
  • Optimised lookup with a Set

Plain old for loops

// Generic helper function that can be used for the three operations:        
function operation(list1, list2, isUnion) {
    var result = [];
    
    for (var i = 0; i < list1.length; i++) {
        var item1 = list1[i],
            found = false;
        for (var j = 0; j < list2.length && !found; j++) {
            found = item1.userId === list2[j].userId;
        }
        if (found === !!isUnion) { // isUnion is coerced to boolean
            result.push(item1);
        }
    }
    return result;
}

// Following functions are to be used:
function inBoth(list1, list2) {
    return operation(list1, list2, true);
}

function inFirstOnly(list1, list2) {
    return operation(list1, list2);
}

function inSecondOnly(list1, list2) {
    return inFirstOnly(list2, list1);
}

// Sample data
var list1 = [
    { userId: 1234, userName: 'XYZ'  }, 
    { userId: 1235, userName: 'ABC'  }, 
    { userId: 1236, userName: 'IJKL' },
    { userId: 1237, userName: 'WXYZ' }, 
    { userId: 1238, userName: 'LMNO' }
];
var list2 = [
    { userId: 1235, userName: 'ABC'  },  
    { userId: 1236, userName: 'IJKL' },
    { userId: 1252, userName: 'AAAA' }
];
  
console.log('inBoth:', inBoth(list1, list2)); 
console.log('inFirstOnly:', inFirstOnly(list1, list2)); 
console.log('inSecondOnly:', inSecondOnly(list1, list2)); 

Arrow functions using filter and some array methods

This uses some ES5 and ES6 features:

// Generic helper function that can be used for the three operations:        
const operation = (list1, list2, isUnion = false) =>
    list1.filter( a => isUnion === list2.some( b => a.userId === b.userId ) );

// Following functions are to be used:
const inBoth = (list1, list2) => operation(list1, list2, true),
      inFirstOnly = operation,
      inSecondOnly = (list1, list2) => inFirstOnly(list2, list1);

// Sample data
const list1 = [
    { userId: 1234, userName: 'XYZ'  }, 
    { userId: 1235, userName: 'ABC'  }, 
    { userId: 1236, userName: 'IJKL' },
    { userId: 1237, userName: 'WXYZ' }, 
    { userId: 1238, userName: 'LMNO' }
];
const list2 = [
    { userId: 1235, userName: 'ABC'  },  
    { userId: 1236, userName: 'IJKL' },
    { userId: 1252, userName: 'AAAA' }
];
  
console.log('inBoth:', inBoth(list1, list2)); 
console.log('inFirstOnly:', inFirstOnly(list1, list2)); 
console.log('inSecondOnly:', inSecondOnly(list1, list2));

Optimising lookup

The above solutions have a O(n²) time complexity because of the nested loop — some represents a loop as well. So for large arrays you’d better create a (temporary) hash on user-id. This can be done on-the-fly by providing a Set (ES6) as argument to a function that will generate the filter callback function. That function can then perform the look-up in constant time with has:

// Generic helper function that can be used for the three operations:        
const operation = (list1, list2, isUnion = false) =>
    list1.filter(
        (set => a => isUnion === set.has(a.userId))(new Set(list2.map(b => b.userId)))
    );

// Following functions are to be used:
const inBoth = (list1, list2) => operation(list1, list2, true),
      inFirstOnly = operation,
      inSecondOnly = (list1, list2) => inFirstOnly(list2, list1);

// Sample data
const list1 = [
    { userId: 1234, userName: 'XYZ'  }, 
    { userId: 1235, userName: 'ABC'  }, 
    { userId: 1236, userName: 'IJKL' },
    { userId: 1237, userName: 'WXYZ' }, 
    { userId: 1238, userName: 'LMNO' }
];
const list2 = [
    { userId: 1235, userName: 'ABC'  },  
    { userId: 1236, userName: 'IJKL' },
    { userId: 1252, userName: 'AAAA' }
];
  
console.log('inBoth:', inBoth(list1, list2)); 
console.log('inFirstOnly:', inFirstOnly(list1, list2)); 
console.log('inSecondOnly:', inSecondOnly(list1, list2));

Community's user avatar

answered Oct 26, 2015 at 22:32

trincot's user avatar

trincottrincot

308k35 gold badges240 silver badges282 bronze badges

short answer:

list1.filter(a => list2.some(b => a.userId === b.userId));  
list1.filter(a => !list2.some(b => a.userId === b.userId));  
list2.filter(a => !list1.some(b => a.userId === b.userId));  

longer answer:
The code above will check objects by userId value,
if you need complex compare rules, you can define custom comparator:

comparator = function (a, b) {
    return a.userId === b.userId && a.userName === b.userName
};  
list1.filter(a => list2.some(b => comparator(a, b)));
list1.filter(a => !list2.some(b => comparator(a, b)));
list2.filter(a => !list1.some(b => comparator(a, b)));

Also there is a way to compare objects by references
WARNING! two objects with same values will be considered different:

o1 = {"userId":1};
o2 = {"userId":2};
o1_copy = {"userId":1};
o1_ref = o1;
[o1].filter(a => [o2].includes(a)).length; // 0
[o1].filter(a => [o1_copy].includes(a)).length; // 0
[o1].filter(a => [o1_ref].includes(a)).length; // 1

answered Feb 19, 2019 at 9:47

Trizalio's user avatar

TrizalioTrizalio

7716 silver badges15 bronze badges

1

Just use filter and some array methods of JS and you can do that.

let arr1 = list1.filter(e => {
   return !list2.some(item => item.userId === e.userId);
});

This will return the items that are present in list1 but not in list2. If you are looking for the common items in both lists. Just do this.

let arr1 = list1.filter(e => {
   return list2.some(item => item.userId === e.userId); // take the ! out and you're done
});

answered Jul 26, 2019 at 16:47

Koushik Das's user avatar

Koushik DasKoushik Das

9,3203 gold badges50 silver badges48 bronze badges

Use lodash’s _.isEqual method. Specifically:

list1.reduce(function(prev, curr){
  !list2.some(function(obj){
    return _.isEqual(obj, curr)
  }) ? prev.push(curr): false;
  return prev
}, []);

Above gives you the equivalent of A given !B (in SQL terms, A LEFT OUTER JOIN B). You can move the code around the code to get what you want!

answered Oct 26, 2015 at 22:15

Bwaxxlo's user avatar

BwaxxloBwaxxlo

1,86013 silver badges18 bronze badges

function intersect(first, second) {
    return intersectInternal(first, second, function(e){ return e });
}

function unintersect(first, second){
    return intersectInternal(first, second, function(e){ return !e });  
}

function intersectInternal(first, second, filter) {
    var map = {};

    first.forEach(function(user) { map[user.userId] = user; });

    return second.filter(function(user){ return filter(map[user.userId]); })
}

answered Oct 26, 2015 at 22:40

Sagi's user avatar

SagiSagi

8,8523 gold badges33 silver badges41 bronze badges

Here is a functionnal programming solution with underscore/lodash to answer your first question (intersection).

list1 = [ {userId:1234,userName:'XYZ'}, 
          {userId:1235,userName:'ABC'}, 
          {userId:1236,userName:'IJKL'},
          {userId:1237,userName:'WXYZ'}, 
          {userId:1238,userName:'LMNO'}
        ];

list2 = [ {userId:1235,userName:'ABC'},  
          {userId:1236,userName:'IJKL'},
          {userId:1252,userName:'AAAA'}
        ];

_.reduce(list1, function (memo, item) {
        var same = _.findWhere(list2, item);
        if (same && _.keys(same).length === _.keys(item).length) {
            memo.push(item);
        }
        return memo
    }, []);

I’ll let you improve this to answer the other questions ;-)

answered Oct 26, 2015 at 22:38

laruiss's user avatar

laruisslaruiss

3,7701 gold badge18 silver badges29 bronze badges

1

This is the solution that worked for me.

 var intersect = function (arr1, arr2) {
            var intersect = [];
            _.each(arr1, function (a) {
                _.each(arr2, function (b) {
                    if (compare(a, b))
                        intersect.push(a);
                });
            });

            return intersect;
        };

 var unintersect = function (arr1, arr2) {
            var unintersect = [];
            _.each(arr1, function (a) {
                var found = false;
                _.each(arr2, function (b) {
                    if (compare(a, b)) {
                        found = true;    
                    }
                });

                if (!found) {
                    unintersect.push(a);
                }
            });

            return unintersect;
        };

        function compare(a, b) {
            if (a.userId === b.userId)
                return true;
            else return false;
        }

answered Oct 30, 2015 at 15:18

Shashi's user avatar

ShashiShashi

1,0922 gold badges17 silver badges32 bronze badges

Понравилась статья? Поделить с друзьями:

Не пропустите также:

  • Как найти gps координаты по адресу
  • Как найти товар в 1с бухгалтерия
  • Найти фильм как страшно красив
  • Как найти скорость прямолинейного движения равномерного движения
  • Как найти чувствительность теста

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии