remove all repeating elements, which I choose with reduce [closed]

I would like to know how I could eliminate all the repeated elements that I give it, using reduce

Example:

Input:

[1,2,4,5,5,5,6,6,7,7,7,7]
5

Output:

[1,2,4,6,6,7,7,7,7]

Code:

const num = 5
const arr = [1,2,4,5,5,5,6,6,7,7,7,7]
arr.reduce( (numberToDel) => {
       ...
})

Answer

In any case, num can’t be an argument in array.reduce().

If you absolutely want to resolve that with a array.reduce() method,
but prefer to use array.filter() method.
both create a new array

const
  num  = 5
, arr1 = [1,2,4,5,5,5,6,6,7,7,7,7]
, arr2 = arr1.reduce((a,c)=>
  {
  if ( c != num) a.push(c)
  return a
  },[])
  
console.log(JSON.stringify( arr2 ))

in “old” JavaScript this look like:

var num  = 5
var arr1 = [1,2,4,5,5,5,6,6,7,7,7,7]

var arr2 = arr1.reduce( myReduce, [] )

function myReduce( accumulator, currentValue )
  {
  if ( currentValue != num) accumulator.push( currentValue )
  return accumulator
  }

console.log(JSON.stringify( arr2 ))

Leave a Reply

Your email address will not be published. Required fields are marked *