1

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]
ZarNi Myo Sett Win
  • 1,353
  • 5
  • 15
  • 37
Manheman
  • 39
  • 1
  • myNewArray =[40, 80, 40, 80,40] you are welcome! ... what are you trying to achieve, an explanation would help. – Aleksei Maide Feb 20 '18 at 06:42
  • Just use a for loop to iterate over all entries, and check whether adjacent elements are the same or not. If they are not, add the element you are comparing to the new array. Edit: Or just use gurvider372's answer, which is easier. – Alperen Görmez Feb 20 '18 at 06:44

4 Answers4

3

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);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

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
gurvinder372
  • 66,980
  • 10
  • 72
  • 94
1

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);
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
0

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>
Smit Patel
  • 2,992
  • 1
  • 26
  • 44