Skip to content

Commit 0fa0b37

Browse files
committed
add move element to end in javascript
1 parent 9cfa0bd commit 0fa0b37

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

Arrays/move_element_to_end.js

+38
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
/*
2+
Move Element to end
3+
Sample Input : [1, 0, 3, 0, 0, 5] To move: 0
4+
Output : [1, 3, 5, 0, 0, 0]
5+
6+
This is a function called MoveElementToEnd that takes an array of integers array and an integer toMove as input,
7+
and returns a modified array with all instances of toMove moved to the end of the array.
8+
9+
The function first initializes an integer variable index to 0, which will keep track of the index of the first
10+
element in the array that is not equal to toMove. Then, it loops through the array using a for loop, and if the
11+
current element is not equal to toMove, it replaces the element at the index position with the current element
12+
and increments the index variable by 1. This effectively shifts all elements that are not equal to toMove to the
13+
beginning of the array.
14+
15+
Next, the function loops through the remaining elements of the array (i.e., those that were not overwritten in
16+
the previous loop), and sets their value to toMove. This effectively moves all instances of toMove to the
17+
end of the array.
18+
19+
Finally, the modified array is returned.
20+
21+
O(n) time | O(1) space - where n is the length of the array
22+
*/
23+
function moveElementToEnd(array, toMove) {
24+
let index = 0; // initialize a variable to keep track of the index where elements should be moved to
25+
for (let i = 0; i < array.length; i++) {
26+
// loop through the entire array
27+
if (array[i] !== toMove) {
28+
// check if the current element is not equal to the element to be moved
29+
array[index] = array[i]; // move the current element to the left side of the array by replacing the element at the current index (index) with the current element (array[i])
30+
index++; // increment the index variable by 1 to keep track of the index where the next non-target element should be moved
31+
}
32+
}
33+
for (let i = index; i < array.length; i++) {
34+
// loop through the remaining elements in the array from index to the end
35+
array[i] = toMove; // set each element to be the target element
36+
}
37+
return array; // return the modified array
38+
}

0 commit comments

Comments
 (0)