javascriptecmascript-6

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.


Solution

  • 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.