I created a "filter" function that receives an array of objects. Each object has an accountId
property. My function is supposed to filter out objects that have a different accountId
. It is, however, pushing an undefined
object in there.
What's wrong with my function?
export const filterItems = (myArray, accountId) => {
let filteredItems = [];
filteredItems.push(myArray.find(items => items.accountId === accountId));
return filteredItems;
}
When I pass an accountId
to my function that is not in the array, the output is an array with one item in it and the item is undefined -- see below:
[
0: undefined
]
What am I doing wrong?
find() method returns an undefined value if the condition implemented in the callback function is never satisfied or you haven't returned a value from the callback function. To solve this, use a type guard to check if find returned a value before accessing properties or methods.
Make sure you use strict equality === to check if a value is equal to undefined . Another alternative is checking if typeof x === 'undefined' . The biggest difference between these two approaches is that, if x has not been declared, x === undefined throws a ReferenceError , but typeof does not.
JavaScript Array find()The find() method returns the value of the first element that passes a test. The find() method executes a function for each array element. The find() method returns undefined if no elements are found. The find() method does not execute the function for empty elements.
The opposite of push() (as the question is titled) is pop() .
You could just filter the array and return an empty array if not found.
export const filterItems = (myArray, accountId) =>
myArray.filter(items => items.accountId === accountId);
Your code always calls .push(). The .find() function returns undefined if the item isn't found.
You can grab the return value from .find()
and then only push the result when it's actually found:
let filteredItems = [];
let item = myArray.find(items => items.accountId === accountId);
if (item !== undefined)
filteredItems.push(item);
return filteredItems;
myArray.find(items => items.accountId === accountId)
is returning undefined
(and it is being pushed to filteredItems
)
Try this instead:
//...
let item = myArray.find(items => items.accountId === accountId);
if(item) {
filteredItems.push(item);
}
//...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With