Ketan Ramteke posted: " Edabit Write a function that moves all the zeroes to the end of an array. Do this without returning a copy of the input array. Examples zeroesToEnd([1, 2, 0, 0, 4, 0, 5]) ➞ [1, 2, 4, 5, 0, 0, 0] zeroesToEnd([0, 0, 2, 0, 5]) " Edabit Write a function that moves all the zeroes to the end of an array. Do this without returning a copy of the input array. Examples zeroesToEnd([1, 2, 0, 0, 4, 0, 5]) ➞ [1, 2, 4, 5, 0, 0, 0] zeroesToEnd([0, 0, 2, 0, 5]) ➞ [2, 5, 0, 0, 0] zeroesToEnd([4, 4, 5]) ➞ [4, 4, 5] zeroesToEnd([0, 0]) ➞ [0, 0] Notes - You must mutate the original array.
- Keep the relative order of the non-zero elements the same.
Solution: 1 2 3 4 5 6 7 8 9 10 11 | function zeroesToEnd(a) { let len = a.length; for (let i = 0; i < a.length; i++) { if (a[i] == 0) { a.splice(i, 1); i--; } } a = [...a, ...Array.from({ length: Math.abs(a.length - len) }, () => 0)]; return a; } |
|
|
|
|
|
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.