我建立了一个看起来像这样的数组:
[
["featured", [7]]
["news", [8,9]]
]
我需要做的是遍历父数组并将子数组中的项目移动到新数组。因此,在上面的示例中,我想将值移动到两个新数组中,如下所示:
var name = ["featured","news"]
var ids = [[7], [8,9]]
我不确定通过遍历父数组来完成此任务的最佳方法吗?
答案 0 :(得分:2)
运行2个循环(单个循环可以提供解决方案)效率低下。使用.forEach
遍历数组中的每个元素。
let arr = [
["featured", [7]],
["news", [8,9]]
];
let names = [];
let val = [];
arr.forEach((i) => {
names.push(i[0]);
val.push(i[1])
});
console.log(names, val); // Will logs ["featured","news"] [[7], [8,9]]
答案 1 :(得分:0)
您可以使用reduce()
和forEach()
let arr = [
["featured", [7]],
["news", [8,9]]
]
let [names,ids] = arr.reduce((ac,a) => {
return ac.forEach((x,i) => x.push(a[i].length === 1 ? a[i][0] : a[i])) || ac;
},[[],[]])
console.log(ids)
console.log(names)
您也可以使用map()
。
let arr = [
["featured", [7]],
["news", [8,9]]
]
let ids = arr.map(x => x[1]);
let names = arr.map(x => x[0]);
console.log(ids)
console.log(names)
答案 2 :(得分:0)
我们还可以使用Array.flat
展平数组并测试元素。
const arr = [
["featured", [7]],
["news", [8,9]]
];
const ids = arr.flat().filter((itm) => Array.isArray(itm));
const name = arr.flat().filter(itm => typeof itm === "string");
console.log(ids);
console.log(name);