9

const values = dataSku.map(sku => {return map.skuInfo[sku].description})

Here, there is some posibility that map.skuInfo[sku] can be null/undefined and I need to filter it. How would it be possible ?

5
  • Use an if statement? Commented May 23, 2018 at 20:20
  • 1
    Array.prototype.filter() (link: MDN) - e.g. const myFilteredArray = myArray.filter(Boolean) (don't necessarily use Boolean like I show but provide an actual comparison, even though that works filtering out "falsy" values) Commented May 23, 2018 at 20:21
  • Can it be other falsey values, or specifically undefined? Commented May 23, 2018 at 20:21
  • With Array.filter() instead of Array.map()? Commented May 23, 2018 at 20:21
  • not existing in the map, so i assume undefined Commented May 23, 2018 at 20:22

4 Answers 4

13

Sounds like you want .filter. It's a higher order function like .map.

const values = dataSku
    .filter(item => item.description !== undefined)

I'm not sure your exact data structure but check it out here! It filters out all non-truthy return values.

Sign up to request clarification or add additional context in comments.

Comments

2

This will solve your problem -

const values = dataSku.map(sku => map.skuInfo[sku]}).filter(skuInfo => typeof skuInfo !== "undefined").map(skuInfo => skuInfo.description);

Comments

1

Can be done like this:

const values = dataSku.map(sku => {
    if (!map.skuInfo[sku]) return;
    return map.skuInfo[sku].description
})

Will return out of the function if map.skuInfo[sku] is falsey.

Comments

0

You can something like as under

const filterNotNullAndUndefined = (sku)  => (sku?.description !== null  && sku?.description !== undefined);
const filterNotNUllAndUndefinedAndNonEmpty = (sku) => (sku?.description)

const sku = [
    {id: 1, 'description': '1'},
    {id: 2, 'description': null},
    {id: 3, 'description': undefined},
    {id: 4, 'description': ''},
    null,
    undefined
];

const result1 = sku?.filter(filterNotNUllAndUndefinedAndNonEmpty);
const result2 = sku?.filter(filterNotNullAndUndefined);

console.log(result1);
console.log(result2);


2 Comments

filterNotNullAndUndefined could be shorter: sku => sku?.description ?? false
oh yes totally missed Nullish coalescing operator (??)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.