我有一个多维数组,如下所示:
var workouts = [
[0, Object, 0, 0, 0],
[Object, 0, 0, 0, 0],
[0, 0, 0, Object, 0]
];
我想展平/合并数组并删除重复项。结果应该是这样的:
[Object, Object, 0, Object, 0]
有可能表演吗?
我的理解是,如果第一个遇到的对象存在,则希望将其保留在给定的列中。
您可以使用.map()
和.reduce()
:
var workouts = [
[0, {id:1}, 0, 0, 0],
[{id:2}, 0, 0, 0, 0],
[0, 0, 0, {id:3}, 0]
];
var res = workouts.reduce(function(a, b) {
return b.map(function(e, i) { return a[i] instanceof Object ? a[i] : e; });
}, []);
console.log(JSON.stringify(res));
派对迟到了,但我仍然想利用:
- CCD_ 3用于将尺寸减小到1
- 用于删除重复数据的
Set
Spread Syntax
用于从该集合中获取数组- CCD_ 6和解析返回以处理对象的重复
以下是代码和一个非常鼓舞人心的帖子1和2:
const myArray = [
[0, {id:1}, 0, 0, 0],
[{id:2}, 0, 0, 0, 0],
[0, 0, 0, {id:2}, 0]
]
const myFlatArray = myArray.flat()
const result = [...new Set(myFlatArray.map(JSON.stringify))].map(JSON.parse)
console.log(JSON.stringify(result))
注意:此解决方案必须支持ES6
var workouts = [
[0, {id:1}, 0, 0, 0],
[{id:2}, 0, 0, 0, 0],
[0, 0, 0, {id:3}, 0]
];
function flattenArray (array){
var newArray = [];
for (i=0; i<array.length; i++){
var subArray = array[i];
for (ii=0; ii<subArray.length; ii++){
if (newArray.indexOf(subArray[ii]) == -1){
newArray.push(subArray[ii]);
}
}
}
return newArray;
}
console.log(flattenArray(workouts));
http://codepen.io/anon/pen/WxLrqL
我愿意这样做;
var workouts = [[0, {a:1}, 0, 0, 0],
[{b:2}, 0, 0, 0, 0],
[0, 0, 0, {c:3}, 0]
],
result = workouts.reduce((p,c) => p = c.map((e,i) => e || p[i] || 0 ),[])
console.log(result);