Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS find function pushing undefined

Tags:

javascript

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?

like image 697
Sam Avatar asked Sep 12 '17 20:09

Sam


People also ask

Why is find returning undefined?

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.

How do I check if JavaScript is undefined?

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.

How to use the find function in JavaScript?

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.

What is the opposite of push () in JavaScript?

The opposite of push() (as the question is titled) is pop() .


3 Answers

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);
like image 133
Nina Scholz Avatar answered Sep 28 '22 08:09

Nina Scholz


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;
like image 21
Pointy Avatar answered Sep 28 '22 07:09

Pointy


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);
}
//...
like image 24
lealceldeiro Avatar answered Sep 28 '22 09:09

lealceldeiro