Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
237 views
in Technique[技术] by (71.8m points)

Filter array of objects based on another array in javascript

Given an array of objects :

people = [
    {id: "1", name: "abc", gender: "m", age:"15" },
    {id: "2", name: "a", gender: "m", age:"25" },
    {id: "3", name: "efg", gender: "f", age:"5" },
    {id: "4", name: "hjk", gender: "m", age:"35" },
    {id: "5", name: "ikly", gender: "m", age:"41" },
    {id: "6", name: "ert", gender: "f", age:" 30" },
    {id: "7", name: "qwe", gender: "f", age:" 31" },
    {id: "8", name: "bdd", gender: "m", age:" 78" },
]

And an array of wanted ids:

id_filter = [1,4,5,8]

How to filter array people to return the target ids defined in id_filter and of gender=m ?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The simplest way to filter is to use the array's filter() function, similar to this:

people.filter(person => id_filter.includes(person.id))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...