Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
JavaScript map() is not saving the new elements?
The map() method creates a new array with transformed elements but doesn't modify the original array. A common mistake is not assigning the returned value from map() to a variable.
The Problem: Not Saving map() Results
map() returns a new array, so you must capture its return value:
let numbers = [1, 2, 3]; // Wrong: map() result is ignored numbers.map(x => x * 2); console.log(numbers); // Original array unchanged // Correct: assign the result let doubled = numbers.map(x => x * 2); console.log(doubled); // New array with transformed values
[ 1, 2, 3 ] [ 2, 4, 6 ]
Example: Adding Index to Array Elements
Here's a practical example that adds the parent array's index to each element:
const addIndexValueToArrayElement = function (arrObject) {
const updatedArrayValue = [];
arrObject.forEach(function (ob) {
const mapValue = ob.map(function (value) {
return value + arrObject.indexOf(ob);
});
updatedArrayValue.push(mapValue);
});
return updatedArrayValue;
};
const output = addIndexValueToArrayElement([
[4, 5],
[7, 56],
[34, 78],
]);
console.log(output);
[ [ 4, 5 ], [ 8, 57 ], [ 36, 80 ] ]
Key Points
-
map()returns a new array ? it doesn't modify the original - Always assign the result:
let newArray = oldArray.map(callback) - Use
forEach()if you don't need a return value - Chain
map()calls:array.map(fn1).map(fn2)
Conclusion
Remember that map() creates a new array and doesn't modify the original. Always capture its return value to save the transformed elements.
Advertisements
