我问一个问题,因为我不知道该怎么做。我尝试使用for
map
reduce
,但我不明白该怎么办。
let array = [3,2,2,5,1,1,7,1];
array.map((e,i,ar)=>{
if(e === ar[i+1] || (e[0] && e[0] === ar[i+1]) ){
return [e,e[1]+1]
}
return e;
})
如何获取数组=> [3,[2,2],5,[1,2],7,1]
中的array
使用Array.filter()
方法代替Array.filter()
。
.map()
您可以减少数组,如果值等于最后一个值,则取一个数组并增加计数器。
let array = [3,2,2,5,1,1,7,1];
// The filtered results will be in a new array
let results = array.filter((e,i,ar)=>{
// Is the next item not equal to the current item?
if(e !== ar[i+1]){
return e; // If so, add it to the filtered results
}
});
console.log(results);
只需使用Array.reduce()得到的。