53

Code:

let names= ["Style","List","Raw"];
let results= names.find(x=> x.includes("s"));
console.log(results);

How to get the names which contain "s" from the array names, currently, I am getting only one element as a result but i need all occurrences.

0

3 Answers 3

123

You have to use filter at this context,

let names= ["Style","List","Raw"];
let results= names.filter(x => x.includes("s"));
console.log(results); //["List"]

If you want it to be case insensitive then use the below code,

let names= ["Style","List","Raw"];
let results= names.filter(x => x.toLowerCase().includes("s"));
console.log(results); //["Style", "List"]

To make it case in sensitive, we have to make the string's character all to lower case.

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

2 Comments

Wonderful 👌🏼
i wonder if (dot)filter and (dot)find are identical except for the number of items returned.
6

Use filter instead of find.

let names= ["Style","List","Raw"];
let results= names.filter(x => x.includes("s"));
console.log(results);

Comments

2

But you can also use forEach() method :

var names = ["Style","List","Raw"];
var results = [];
names.forEach(x => {if (x.includes("s") || x.includes("S")) results.push(x)});
console.log(results); // [ 'Style', 'List' ]

Or if you prefere :

names.forEach(x => {if (x.toLowerCase().includes("s")) results.push(x)});

1 Comment

If you use filter what you are doing in forEach will be done by filter. Filter returns an array whereas forEach won't return anything. So it is better readable :)

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.