Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chain push along with filter, map etc in JavaScript?

Tags:

javascript

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}
        />
      )
    })
)
like image 993
Evanss Avatar asked Jan 03 '23 05:01

Evanss


2 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({ ... })

like image 183
kind user Avatar answered Jan 05 '23 20:01

kind user


.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])
like image 43
gurvinder372 Avatar answered Jan 05 '23 19:01

gurvinder372