Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find multiple elements in Array - Javascript ,ES6

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.

like image 739
Gowtham Avatar asked Jul 27 '16 16:07

Gowtham


People also ask

How do I find an element in an array of arrays?

If you need the index of the found element in the array, use findIndex() . If you need to find the index of a value, use Array.prototype.indexOf() . (It's similar to findIndex() , but checks each element for equality with the value instead of using a testing function.)

How do you check if there are duplicates in an array JavaScript?

To check if an array contains duplicates: Use the Array. some() method to iterate over the array. Check if the index of the first occurrence of the current value is NOT equal to the index of its last occurrence. If the condition is met, then the array contains duplicates.

Is there a SUM () in JavaScript?

sum() function in D3. js is used to return the sum of the given array's elements. If the array is empty then it returns 0. Parameters: This function accepts a parameters Array which is an array of elements whose sum are to be calculated.


2 Answers

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.

like image 154
Rajaprabhu Aravindasamy Avatar answered Nov 04 '22 14:11

Rajaprabhu Aravindasamy


Use filter instead of find.

let names= ["Style","List","Raw"]; let results= names.filter(x => x.includes("s")); console.log(results); 
like image 30
ingleback Avatar answered Nov 04 '22 16:11

ingleback