如何在JavaScript中借助索引数组从原数组生成新数组?
根据索引数组生成新数组的实现方法
你需要从原数组list中,根据索引数组index里的位置值,提取对应元素组成新数组,这里有几种简单直接的实现方式:
方法一:使用Array.map()(最简洁)
map方法可以直接遍历索引数组,取出原数组对应位置的元素,代码如下:
const list = [ { id: 0, name: "Ken" }, { id: 1, name: "Ryu" }, { id: 2, name: "Sakura" }, { id: 3, name: "Vega" } ]; const index = [1, 3]; // 生成目标数组 const filteredList = index.map(i => list[i]); console.log(filteredList); // 输出结果: // [{ id: 1, name: "Ryu" }, { id: 3, name: "Vega" }]
方法二:处理无效索引的情况
如果担心index数组里存在超出原数组长度的无效索引,可以在map后加filter过滤掉undefined:
const filteredList = index.map(i => list[i]).filter(item => item !== undefined);
方法三:使用Array.reduce()构建数组
通过reduce逐步收集有效元素,同样可以处理无效索引:
const filteredList = index.reduce((result, currentIndex) => { const item = list[currentIndex]; if (item) { result.push(item); } return result; }, []);
内容的提问来源于stack exchange,提问作者sahasrabhuja neuron
相关产品推荐
相关产品推荐

