For a 2D array:
var fruits = [["Banana", "Orange", "Apple", "Pear"],
["Banana", "Orange", "Apple", "Pear"],
["Banana", "Orange", "Apple", "Pear"],
["Banana", "Orange", "Apple", "Pear"]];
why the difference between map and for loop?
var newArrayMap = fruits.map(f => f.splice(1,2));
console.log(newArray);
[["Orange", "Apple"], ["Orange", "Apple"], ["Orange", "Apple"], ["Orange", "Apple"]]
for (var i = fruits.length - 1; i >= 0; i--){
fruits[i].splice(1,2);
}
console.log(fruits);
[["Banana", "Pear"], ["Banana", "Pear"], ["Banana", "Pear"], ["Banana", "Pear"]]
CodePudding user response:
Array#splice returns the deleted parts of the array.
In the first loop with map, you take the returned value of splice.
In the second loop with for, you never use the returned value of splice. splice mutates the array and because of that, you get an array without unwanted parts.
