Why Does JavaScript Map Function Return Undefined

Why does JavaScript map function return undefined?

You aren't returning anything in the case that the item is not a string. In that case, the function returns undefined, what you are seeing in the result.

The map function is used to map one value to another, but it looks like you actually want to filter the array, which a map function is not suitable for.

What you actually want is a filter function. It takes a function that returns true or false based on whether you want the item in the resulting array or not.

var arr = ['a','b',1];
var results = arr.filter(function(item){
return typeof item ==='string';
});

Why map is returning [undefined]? and how can i solve that?

Why is JS Map Function Returning Undefined?

Unsure what you're attempting to accomplish, but:

Try something like this to return a sum of all pctSavings:

const totalPercents = cars.reduce((sum, el) => {
const pctSavings = +(el[0].getAttribute("percent-savings"));
if (pctSavings > 0) sum += pctSavings;
return sum;
}, 0);

To return an array of pctSavings, simply do this:

const totalPercents = cars.reduce((arr, el) => {
const pctSavings = +(el[0].getAttribute("percent-savings"));
if (pctSavings > 0) arr.push(pctSavings);
return arr;
}, []);

To get the max pctSavings do this:

let maxPctSavings = 0;
cars.forEach(el => {
const pctSavings = +(el[0].getAttribute("percent-savings"));
if (pctSavings > maxPctSavings) maxPctSavings = pctSavings
});
console.log(maxPctSavings) // this is your answer

map function return undefined

The second parameter of the call back function of Array.prototype.map() is the index that have numeric value, using index on them will always return undefined.

To access the first key from each object in the array you can try the following using Destructuring assignment:

let aRa = [
{hero:"troll",
age:12,
hair:"red",},

{hero:"rikky",
age:11,
hair:"purple"},

{hero:"techies",
age:40,
hair:"yellow"},
]

let joyRide = aRa.map(({hero}) => hero);
console.log(joyRide)

Prevent arrray.map returning undefined when condition/callback is not met

You can use Array.filter() to removing the undefined values by using Boolean as the predicate: