Hello and here is my problem.I have a task,i need to remove elements from an array and push them into another array and then return the array with removed elements. For example, in this case i have to remove all 0 values, and push them into 'a' array and then return 'a' array with there 0 values. I removed 0 values from the array by using splice method and loop, but i don't realy know how to push removed elemts into 'a' array, i've tried to use push method but i does not work for me. Hope you'll help me.Thank you everyone.
function moveZeros(array) { var a = []; for (var i = array.length - 1; i--;) { if (array[i] == "0") { array.splice(i, 1); } } return a; } moveZeros([1, 2, 0, 1, 0, 1, 0, 3, 0, 1]);
Using push
should work. The .splice
method will return an array with the removed elements, and you can use the spread operator ...
to pass it as a set of arguments to push
:
function moveZeros(array) { var a = []; for (var i = array.length - 1; i >= 0; i--) { if (array[i] == "0") { a.push(...array.splice(i, 1)); } } return a; } const array = [0, 1, 2, 0, 1, 0, 1, 0, 3, 0, 1, 0, 0]; console.log(moveZeros(array)); console.log(array)
Finally, you should put the i--
as the final part of the loop so that it only executes when each iteration finishes (instead of as they begin). Then, change your condition to be i >= 0
so that you don't miss a zero at the front of the array.
Array.splice()
returns an array of removed elements, and you can use Array.concat()
to add them to the a
array.
Notes:
i
to array.length
without the -1, since the condition i--
is checked before the execution of the loop's body. a
to the removed elements to maintain the original order. function moveZeros(array) { var a = []; for (var i = array.length; i--;) { if (array[i] === 0) { a = array.splice(i, 1).concat(a); } } return a; } var result = moveZeros([1, 2, 0, 1, 0, 1, 0, 3, 0, 1, 0]); // I've added a last 0 to the array to show that all items were removed console.log(result);
You could iterate from the end and splice the array if necessary. This solution mutates the array
.
function moveZeros(array) { var i = array.length, a = []; while (i--) { if (array[i] === 0) { a.push(array.splice(i, 1)[0]); } } return a; } var array = [1, 2, 0, 1, 0, 1, 0, 3, 0, 1]; console.log(moveZeros(array)); console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.