如果下一个元素等于上一个元素,如何减少JS数组的长度

问题描述 投票:0回答:3

我问一个问题,因为我不知道该怎么做。我尝试使用formapreduce,但我不明白该怎么办。

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

javascript arrays
3个回答
0
投票

使用Array.filter()方法代替Array.filter()

.map()

0
投票

您可以减少数组,如果值等于最后一个值,则取一个数组并增加计数器。

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);

0
投票

只需使用Array.reduce()得到的。

© www.soinside.com 2019 - 2024. All rights reserved.