R
R
roovwhite2015-06-04 18:57:22
JavaScript
roovwhite, 2015-06-04 18:57:22

How to compare two arrays of different length and return matching elements?

Hello.
There are two arrays, for example,
arr1 = [two, one];
arr2 = [one, four, five];
Can you please tell me how they can be compared and return matches?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
I
Igor Belikov, 2015-06-04
@roovwhite

function get_unique_array(array1, array2) {
  return array1.filter(function(val) {
    return array2.indexOf(val) != -1;
  });
}

var
  arr_1 = ['a', 'b', 'c'],
  arr_2 = ['b', 'c', 'd', 'e'];

console.log(get_unique_array(arr_1, arr_2)); // ["b", "c"]

update
answer updated with scapp example

S
scapp, 2015-06-05
@scapp

var overlap = array1.filter(function(val) {
return array2.indexOf(val) != -1;
});

P
Pavel Kononenko, 2015-06-04
@premas

If the task is to conveniently work with arrays and objects, then do not suffer. Use underscore. In your case, the intersection method is ideal

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question