你可以在JavaScript中如何利用另一个不同的数组从原始数组创建一个新数组?

huangapple go评论78阅读模式
英文:

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:&quot;Ken&quot;},{id:1,name:&quot;Ryu&quot;},{id:2,name:&quot;Sakura&quot;},{id:3,name:&quot;Vega&quot;},];

const index = [1, 3];

const filteredList = list.filter(({id}) =&gt; index.includes(id))

console.log(filteredList);

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年2月27日 18:37:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/75579381.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定