Manheman
Manheman

Reputation: 39

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]

Upvotes: 1

Views: 96

Answers (4)

Nina Scholz
Nina Scholz

Reputation: 386848

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

Upvotes: 3

Smit Patel
Smit Patel

Reputation: 3267

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>

Upvotes: 0

Pranav C Balan
Pranav C Balan

Reputation: 115272

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

Upvotes: 1

gurvinder372
gurvinder372

Reputation: 68433

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

Upvotes: 1

Related Questions