Hi I am having an array like below and trying to push the item on map, but i am not able to push, Please tell what wrong i am doing here.
firstClassPrices: [
[
"Kan ej ombokas",
"431",
"SEK",
"Företagspris"
],
[
"Kan ombokas",
"525",
"SEK",
"Företagspris"
]
]
trying to push '1' like below:
let ticketi = firstClassPrices.map((price) => {
price.push("1");
});
i need o/p as
firstClassPrices: [
[
"Kan ej ombokas",
"431",
"SEK",
"Företagspris",
"1"
],
[
"Kan ombokas",
"525",
"SEK",
"Företagspris",
"1"
]
]
4 Answers 4
You have to return the price
const firstClassPrices = [
[
"Kan ej ombokas",
"431",
"SEK",
"Företagspris"
],
[
"Kan ombokas",
"525",
"SEK",
"Företagspris"
]
];
let ticketi = firstClassPrices.map((price) => {
// skip if price already includes 1
if (!price.includes("1")) {
price.push("1");
}
return price;
});
console.log(ticketi);
3 Comments
firstClassPrices and ticketi reference the same nested arrays. There is little added value in using .map() if you are going to modify the original array also.Your approach mutates the old array and maps undefined.
Instead, you could map the old and new content of the array.
This approach does not mutate the old data.
let ticketi = firstClassPrices.map(price => [...price, '1']);
1 Comment
1 should be of type stringYou can use Array.prototype.map() combined with Array.prototype.concat()
Code:
const firstClassPrices = [["Kan ej ombokas","431","SEK","Företagspris"],["Kan ombokas","525","SEK","Företagspris"]]
const ticketi = firstClassPrices.map(p => p.concat('1'))
console.log(ticketi)
Comments
Since you want to mutate the original arrays, you can use the function Array.prototype.forEach.
The problem you're facing is regarding the missing return value inside of the map's handler, so basically, the handler is returning undefined
const array = [ [ "Kan ej ombokas", "431", "SEK", "Företagspris" ], [ "Kan ombokas", "525", "SEK", "Företagspris" ]],
handler = (a) => a.push("1");
array.forEach(handler);
console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
.map()while not returning any elements from its callback function so the return value (which you store inticketiwill only containundefinedvalues. But the originalfirstClassPriceswill contain what you are looking for.