How to map items without undefined value in javascript with Array.prototype.map and without Array.prototype.filter()
Code:
var testArray = [
{
name: "toto",
totoNumber: "1",
},
{
name: "tata",
totoNumber: "2",
},
{
mame: "error",
},
]
var listOfToto = testArray.map(x => x.totoNumber);
var listOfToto2 = testArray.map(x => x.totoNumber ? x.totoNumber : undefined);
var listOfToto3 = testArray.filter(x => x.totoNumber).map(x => x.totoNumber);
console.log(listOfToto);
console.log(listOfToto2);
console.log(listOfToto3);
Values:
Array ["1", "2", undefined]
Array ["1", "2", undefined]
Array ["1", "2"]
I want to get the last array (["1", "2"]) without using Array.prototype.filter()
(maybe with something else than Array.prototype.map())
Other source:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
Why does javascript map function return undefined?
https://codewithhugo.com/avoiding-falsy-values-in-javascript-arrays/
array.filter(). I think you're concerned about the fact that you're using two loops (filter, thenmap). Don't be.reduceto build your new array and only include elements when they need to be there, but usingmapandfilterwill be much easier to read and to maintaintestArray.map(x => x.totoNumber).filter(e => e)(although if you can have zero as a value you might want to explicitly check for!== undefined)