1

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.

3
  • Any special reason why you don't want loops? Commented Oct 12, 2017 at 13:40
  • 1
    Probably his teacher said not to do it. Commented Oct 12, 2017 at 13:40
  • I working with quite a large number of data so the for loops take long time to execute. Last one I did took around 20 seconds Commented Oct 12, 2017 at 13:47

4 Answers 4

3
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

Sign up to request clarification or add additional context in comments.

2 Comments

Shouldn't it return indexOf(x) > -1?
@pete 0 >= 0 is the same as 0 > -1
0

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)

Comments

0

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);

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.