我正在尝试使用reduce()"整理"顺序组合一组数组,因此具有相似索引的项目在一起.例如:
input = [["one","two","three"],["uno","dos"],["1","2","3","4"],["first","second","third"]]
output = [ 'first','1','uno','one','second','2','dos','two','third','3','three','4' ]
Run Code Online (Sandbox Code Playgroud)
只要它们在一起,具有相似索引的项目的顺序无关紧要,因此结果'one','uno','1'...是如上所述.我想尽可能使用不可变变量.
我有办法:
const output = input.reduce((accumulator, currentArray, arrayIndex)=>{
currentArray.forEach((item,itemIndex)=>{
const newIndex = itemIndex*(arrayIndex+1);
accumulator.splice(newIndex<accumulator.length?newIndex:accumulator.length,0,item);
})
return accumulator;
})
Run Code Online (Sandbox Code Playgroud)
但它不是很漂亮而且我不喜欢它,特别是因为它在forEach方法中改变累加器的方式.我觉得必须有一个更优雅的方法.
我不敢相信之前没有人问过这个问题,但是我尝试了一堆不同的查询而无法找到它,所以请告诉我它是否在那里而我错过了它.有没有更好的办法?
为了澄清评论中的每个问题,我希望能够在不改变任何变量或数组的情况下执行此操作,因为我正在使用accumulator.splice和仅使用函数方法,例如.map,或者.reduce不使用类似的变异循环.forEach.
var userids = userbody.contacts.map(function(obj){
if((obj.iAccepted=='true')&&(obj.contactAccepted=='true')) {
console.log(true);
return obj.userID //return obj.userID
}
});
Run Code Online (Sandbox Code Playgroud)
这将给出如下结果:
['0','35','37','30','34','36','33','32',undefined,'332','328','337','333' ,undefined]
我想跳过数组中未定义的元素.
我有一些我想要转换的数据Array.prototype.map.但是在map函数中,外部函数调用可能会抛出错误.我想捕获此错误,而不是将该特定对象添加到返回的数组.目前我只是返回undefined然后使用Array.prototype.filter清除未定义的值,但这似乎是一种肮脏的方式来做到这一点.
为了澄清,我正在寻找这个功能:
['apple','pear','banana', 'peach'].map(function(fruit){
if (fruit === 'apple') {
return undefined;
}
return 'I love to eat ' + fruit;
});
// ['I love to eat pear', 'I love to eat peach', 'I love to eat banana']
Run Code Online (Sandbox Code Playgroud)
这个的任何现有的实现?我只是以错误的方式解决这个问题吗?