0

I've tried a few solutions to this and have had a look round on here but can't seem to get this working.

I have 2 arrays, and want to check if any of the items in the array contain any of the strings in the other array.

const stepsShown = ["ref2", "ref7"];
const items = [
{ name: "item1", element: "ref1"},
{ name: "item2", element: "ref2"}
];
const refsExist = items.some((r) =>{stepsShown.indexOf(r.element);});

In this example I would expect refsExist to be true

I think I am a little muddled in my syntax! Can anyone help please? :)

1
  • You want includes, not indexOf - and you need to return the result from the function Commented Aug 28, 2017 at 18:50

2 Answers 2

3

You have it almost right, except that you need to test for a non -1 value, and your arrow function shouldn't have brackets.

If your arrow function consists of a single expression, you don't need brackets:

items.some(r=>stepsShown.indexOf(r.element)!=-1);

If your arrow function includes statements or multiple expressions, you need curly brackets. When you use curly brackets, you must include an explicit return statement.

items.some(r=>{
    for(some;thing;) { ... }
    return otherThing;
});

Instead of relying on the less-readable .indexOf(..)!=-1 test, you can simply use includes:

items.some(r=>stepsShown.includes(r.element));
Sign up to request clarification or add additional context in comments.

Comments

0

You can find an element and later check if it is undefined or not

const stepsShown = ["ref2", "ref7"];
const items = [
{ name: "item1", element: "ref1"},
{ name: "item2", element: "ref2"}
];
const refsExist = items.find((r) =>{    
    return stepsShown.indexOf(r.element)>-1;
});

console.log(refsExist !== undefined);

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.