My question is, how can I find all array indexes by a word ?
[
{name: "Jeff Crawford", tel: "57285"},
{name: "Jeff Maier", tel: "52141"},
{name: "Tim Maier", tel: "73246"}
]
If I search for "Jeff", I want to get:
[
{name: "Jeff Crawford", tel: "57285"},
{name: "Jeff Maier", tel: "52141"},
]
Use
.filter
:If you want to check to see if "Jeff" is anywhere rather than only at the beginning, use
.includes
instead:These are ES6 features. For ES5, use
indexOf
instead:Use array
filter
method along withindexOf
.filter
will return a new array of matched element. In side the filter callback function check for the name where theindexOf
the keyword is not-1
. That is the name should contain the keywordTo make it more versatile, you could take a function which takes an array of objects, the wanted key and the search string, wich is later used as lower case string.
Use
Array#map
on the original array and return the indices. Then filter out theundefined
values: