Reputation: 23563
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}
/>
)
})
)
Upvotes: 5
Views: 2548
Reputation: 1
.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');
Upvotes: 0
Reputation: 68393
.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])
Upvotes: 5
Reputation: 41893
.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({ ... })
Upvotes: 7