Chain push along with filter, map etc in JavaScript?

Viewed 1976

I have a function which returns an array which has filter, sort and map. How can I push a new item into the array before its sorted?

When I try the following I get an error saying push isnt a function.

return (
  myArray
    .filter((item) => {
      return item.value > 2;
    })
    .push(newThiny) // This doesn't work
    .sort((a, b) => {
      if (a.name < b.name)
        return -1;
      if (a.name > b.name)
        return 1;
      return 0;
    })
    .map((item) => {
      return (
        <ChooseAnExercises
          key={item.name}
          name={item.name}
          active={item.active}
          setNumber={this.props.number}
          updateValue={this.props.updateValue}
        />
      )
    })
)
3 Answers

.push(newThiny) will return a number so .sort function will throw an error, since it doesn't work on numbers, only on arrays.

I would suggest you to use .concat instead.

.concat(newThiny).sort({ ... })

.push(newThiny) // This doesn't work

Push returns the length of the array rather than the array itself.

Rather than push try concat

.concat([newThiny])

.push() return a length of array. You can wrap your expression with ()

See the Example:

var arr = [ 0, 1, 2, 3, 4];

var arr2 = arr.filter( item => item > 2).push('Some');

console.log(arr2, 'doesnt works. You get the length of array');

(b = arr.filter(item => item > 2)).push('Some');

console.log(b, 'Works Correctly. In Array');

Related