developer
developer

Reputation: 331

Avoid null values while filtering javascript array

How can I filter for "mna" ===1 and ignore null values

const words = [null, null,  {"mna":1}, {"mna":2}, {"mna":1}];

    const result = words.filter(word => word.mna === 1);

Upvotes: 2

Views: 811

Answers (3)

mplungjan
mplungjan

Reputation: 178402

Alternatively use

Optional chaining:

const words = [null, null,  {"mna":1}, {"mna":2}, {"mna":1}];
const result = words.filter(word => word?.mna === 1);
console.log(result);

Works also when the entry exists but the element is missing

const words = [{
  "count": "3",
  "noMNA": true
}, {
  "count": "3",
  "mna": 1
}, {
  "count": "2",
  "mna": 2
}, {
  "count": "3",
  "mna": 1
}];
const result = words.filter(word => word?.mna === 1);
console.log(result);

Upvotes: 1

Klaycon
Klaycon

Reputation: 11080

Just add it to the condition so you don't try to access mna unless it's truthy (null values are falsy so they will cause the condition to short circuit early)

const words = [null, null,  {"mna":1}, {"mna":2}, {"mna":1}];

const result = words.filter(word => word && word.mna === 1);

console.log(result);

Upvotes: 2

mickl
mickl

Reputation: 49985

You can add word && word.mna === 1 to check if word is defined first. The value will be filtered out if it's falsy (null,undefined)

const words = [null, null,  {"mna":1}, {"mna":2}, {"mna":1}];
const result = words.filter(word => word && word.mna === 1);
console.log(result);

Upvotes: 1

Related Questions