简体   繁体   中英

Reduce array with javascript

I have an array like this :

myArray = [40, 40, 40, 40, 40, 80, 40, 40, 40, 40, 40, 40, 40, 40, 80, 40, 40, 40, 40, 40, 40, 40, 40]

I would like to reduce it like this :

myNewArray =[40, 80, 40, 80,40]

You could check the predecessor and the actual value. If different, then take that item for the result set.

 var array = [40, 40, 40, 40, 40, 80, 40, 40, 40, 40, 40, 40, 40, 40, 80, 40, 40, 40, 40, 40, 40, 40, 40], filtered = array.filter((v, i, a) => a[i - 1] !== v); console.log(filtered); 

So you want to ignore the consecutive same numbers, use reduce

var output = arr.reduce( ( a,c) => (a.slice(-1) == c ? "" : a.push(c), a) ,[]);

Demo

 var output = [40, 40, 40, 40, 40, 80, 40, 40, 40, 40, 40, 40, 40, 40, 80, 40, 40, 40, 40, 40, 40, 40, 40].reduce( ( a,c) => (a.slice(-1) == c ? "" : a.push(c), a) ,[]); console.log ( output ); 

Explanation

  • a.slice(-1) == c checks if last element is same as current element
  • If not, then push c to a
  • Return the accumulator value a

Use Array#reduce method where insert a value into a new array by comparing the previous value in the main array or last inserted value in the result array.

 myArray = [40, 40, 40, 40, 40, 80, 40, 40, 40, 40, 40, 40, 40, 40, 80, 40, 40, 40, 40, 40, 40, 40, 40]; var res = myArray.reduce(function(arr, v, i) { //check index is 0 or compare previously inserted value is same // then insert current value in the array if (!i || (i && arr[arr.length - 1] != v)) arr.push(v); // or alternatively compare previous value in the array itself // if (!i || (i && myArray[i - 1] != v)) arr.push(v); // return array refenrence return arr; // set initioal value as array for result }, []); console.log(res); 

Above answers are absolutely correct, As a beginner you can understand well from this.

<script>
myArray = [40, 40, 40, 40, 40, 80, 40, 40, 40, 40, 40, 40, 40, 40, 80, 40, 40, 40, 40, 40, 40, 40, 40];
newArray = [];

var lastValue;
for(var i = 0; i <= myArray.length; i++)
{
    if(myArray[i] != lastValue) // if the value doesn't match with last one.
    {
       newArray.push(myArray[i]);  // add to new array.
    }
    lastValue = myArray[i];
}
alert(newArray.join(','));

</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM