I'm trying to change the type of each element of the array to numeric, but the string iterating over the array and transforming seems to be ignored and the original array remains the same.
arr.forEach(item => Number(item));
This is because you are not assigning it to the source array or not replacing the array with the new one that has all elements of the number type
You can also make it short as
arr.map(Number)
1) Assigining the converted number(from string to number type) back to source array index
const arr = ["1", "2", "5", "7"];
arr.forEach((n, i, src) => (src[i] = Number(n)));
console.log(arr);
2) Assigning a new array that has all elements converted to type number back to arr variable.
let arr = ["1", "2", "5", "7"];
arr = arr.map(n => Number(n));
console.log(arr);
// Foreach does not return anything, so any update you want to save has to be done manually
arr = ['1','200'];
arr.forEach(item => Number(item));
console.log(arr);
// here you are updating the orinal array
arr = ['1','200'];
arr.forEach((item, i ) => arr[i] = Number(item));
console.log(arr);
// here you are creating a new array without impacting the existing array
arr = ['1','200'];
let newArr = arr.map((item) => Number(item));
console.log(arr);
console.log(newArr);
forEach doesn't return anything. It just mutates the array that it's given.
Its callback accepts three arguments. The first is the array element, the second is the index of that element, and the last is the array itself. We only have concern ourselves with the first two in this example.
Because forEach mutates the array you need to assign the the result of coercing the string to a number back to the array index.
const arr = ['1', '2', '3'];
arr.forEach((item, i) => {
arr[i] = Number(item);
});
console.log(arr);
The alternative is to use map which creates a new array. We can use Number directly as the callback because it only accepts one argument which will be the array element.
const arr = ['1', '2', '3'];
const newArr = arr.map(Number);
console.log(newArr);