英文:
How can I create a new array from an original array making use of ONE MORE DIFFERENT ARRAY in Javascript?
问题
这里有两个简单的数组,一个是原始列表,另一个是从原始列表中选择的索引数组。
我只想根据选定的索引数组重新创建一个新数组。
这是我的代码。
const list = [{
id: 0,
name: "Ken"
},
{
id: 1,
name: "Ryu"
},
{
id: 2,
name: "Sakura"
},
{
id: 3,
name: "Vega"
}
]
const index = [1, 3]
//我想获得一个新数组,像这样利用上面的两个数组:
filteredList = [
{
id: 1,
name: "Ryu"
},
{
id: 3,
name: "Vega"
}
]
我尝试了很多方法,但只是搞乱了,陷入了困境。
你可以如何完成这个任务?
谢谢。
英文:
Here are two simple arrays, one is an original list, the other is a selected index from the original one.
I just want to re-create a new array, based on the selected index array.
Here is my code.
const list = [{
id: 0,
name: "Ken"
},
{
id: 1,
name: "Ryu"
},
{
id: 2,
name: "Sakura"
},
{
id: 3,
name: "Vega"
}
]
const index = [1, 3]
//I want to get a new array like this, making use of both of the arrays above:
filterdList = [
{
id: 1,
name: "Ryu"
},
{
id: 3,
name: "Vega"
}
]
I tried lots of things but I just messed up and was just stack.
How would you accomplish this?
Thank you in advance
答案1
得分: 1
你可以使用 Array.prototype.filter。
const list = [{ id: 0, name: "Ken" }, { id: 1, name: "Ryu" }, { id: 2, name: "Sakura" }, { id: 3, name: "Vega" }];
const index = [1, 3];
const filteredList = list.filter(({ id }) => index.includes(id));
console.log(filteredList);
英文:
You can use Array.prototype.filter
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
const list=[{id:0,name:"Ken"},{id:1,name:"Ryu"},{id:2,name:"Sakura"},{id:3,name:"Vega"},];
const index = [1, 3];
const filteredList = list.filter(({id}) => index.includes(id))
console.log(filteredList);
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论