-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path23.js
More file actions
53 lines (36 loc) · 1.01 KB
/
23.js
File metadata and controls
53 lines (36 loc) · 1.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// move all zero to first of the array
var array = [1,2,3,4,0,0,2,0];
// -------------------------------------------------------------------
var resultArray = [];
var length = array.length;
// inserting all zeros
for(i=0;i<length;i++){
if(array[i] === 0){
resultArray[resultArray.length] = array[i];
}
}
/// inserting other numbers
for(i=0;i<length;i++){
if(array[i] !== 0){
resultArray[resultArray.length] = array[i]
}
}
console.log(resultArray)
// -------------------------------------------------------------------
// method 2 using in-built methods
for(let i=0;i<array.length;i++){
if(array[i]==0){
array.unshift(array.splice(i,1)[0])
}
}
// -------------------------------------------------------------------
// method 3 O(N)T O(1)S
const output = [];
for(let i=0;i<array.length;i++){
if(array[i] !== 0) {
output.push(array[i])
}else{
output.unshift(0)
}
}
// -------------------------------------------------------------------