Reputation: 242
So let's say we have two arrays
const arr1 = [1, 2, 3, 4, 5];
const arr2 = [6, 7, 8, 9, 10, 4, 5,];
I want to return just the first matching value without doing two for loops. So not by taking first value from arr1
look for it in arr2
then second value ect.
I this case I would need to return 4
.
Working in React/Redux enviroment without jQuery possible.
Upvotes: 1
Views: 81
Reputation: 386654
You could use the power of Set
.
const
arr1 = [1, 2, 3, 4, 5],
arr2 = [6, 7, 8, 9, 10, 4, 5],
result = arr2.find((s => a => s.has(a))(new Set(arr1)));
console.log(result);
Upvotes: 0
Reputation: 92854
Ecmascript5 solution (with Array.some()
function):
var arr1 = [1, 2, 3, 4, 5],
arr2 = [6, 7, 8, 9, 10, 4, 5,],
result;
arr2.some(function(n){ return arr1.indexOf(n) !== -1 && (result = n) })
console.log(result);
Upvotes: 0
Reputation: 122057
You can use find()
with includes()
method.
const arr1 = [1, 2, 3, 4, 5];
const arr2 = [6, 7, 8, 9, 10, 4, 5,];
var r = arr1.find(e => arr2.includes(e));
console.log(r)
Upvotes: 0
Reputation: 1312
const arr1 = [1, 2, 3, 4, 5];
const arr2 = [6, 7, 8, 9, 10, 4, 5,];
arr1.find((x) => arr2.indexOf(x) >=0);
That'll grab the first match
Upvotes: 3