How can I yield the same output in Javascript, given this Python example?
I want to loop over an array and check a value, if condition met, store it.
JavaScript
x
16
16
1
arr1 = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
2
13, 13, 0, 0, 0, 0, 0, 0, 0, 0, 13, 13, 0, 0, 0, 0, 0, 0,
3
0, 0, 0, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 14, 0, 0,
4
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0,
5
0, 0]
6
7
new_labels = []
8
previous = None
9
for l in arr1:
10
if l != previous:
11
new_labels.append(l)
12
previous = l
13
14
# expected:
15
[0, 7, 0, 13, 0, 13, 0, 15, 0, 14, 0, 2, 0]
16
Advertisement
Answer
This can be done more simply with Array#filter
.
JavaScript
1
3
1
let arr1 = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,13, 13, 0, 0, 0, 0, 0, 0, 0, 0, 13, 13, 0, 0, 0, 0, 0, 0,0, 0, 0, 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 14, 0, 0,0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0,0, 0];
2
let res = arr1.filter((x, i) => x !== arr1[i - 1]);
3
console.log(JSON.stringify(res));