I am working on what i thought is a simple algorithm:
Task: Look at the given array, take only the even numbers and multiply them by 2. The catch is to modify the array in its place and NOT create a new array.
I can loop/map through an array and figure out what numbers are even, so I got this far:
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
arr.forEach((x, y) => {
if (x % 2 !== 0) {
// I would like to splice those numbers,
// but can't figure out how to do it?
}
})
Again, the catch is that modifying the original array is not allowed, returning 4, 8, 12, 16, and 20.
CodePudding user response:
This is not a good approach in my opinion, but if you insist on modifying the existing array without creating a new one, this should do the job:
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let i = 0;
while (i < arr.length) {
if (arr[i] % 2 === 0) {
arr[i] *= 2;
} else {
arr.splice(i, 1);
i--;
}
i ;
}
console.log(arr.join(", "));
The i-- comes into play, because when you splice the current index (where the next element will be after the splice) and you execute i , it's going to skip the current index. The same effect can possibly be achieved by adding i in the if block and remove the i-- in the else block.
CodePudding user response:
First of all. Why would you do that? If you don't want the old array just take the new one.
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
const evenNumbers = arr.filter(item => item % 2 === 0)
Unless it's something required, explore all Js Array methods, always are multiple ways to get to an answer. Try to make your life easy.
Like the example before you will have the old and the new. Take wherever you need.
CodePudding user response:
You could take a different approach and loop from start by using a new index for all items to keep and later adjust the length of the array.
const
array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let l = 0; i = 0;
while (i < array.length) {
console.log(...array);
if (array[i] % 2 === 0) array[l ] = array[i] * 2;
i ;
}
array.length = l;
console.log(...array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
CodePudding user response:
You can use Array.prototype.filter() and Array.prototype.map()
Code:
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
const result = arr
.filter(n => n % 2 === 0)
.map(n => n * 2)
console.log(result)
CodePudding user response:
Could this be what you had in mind?
const arr=[1,2,3,4,5,6,7,8,9,10];
for (let i=arr.length-1;i>=0;i--)
if(arr[i]%2>0) arr.splice(i,1)
arr.forEach((v,i,a)=> a[i]=v*2)
console.log(arr);
As you want to remove elements from an array you are looping over, it is important that you start from the end and work your way down to 0
since going forward you would skip an element as soon as you remove one.