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.
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]
new_labels = []
previous = None
for l in arr1:
    if l != previous:
        new_labels.append(l)
        previous = l
# expected: 
[0, 7, 0, 13, 0, 13, 0, 15, 0, 14, 0, 2, 0]
Advertisement
Answer
This can be done more simply with Array#filter.
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]; let res = arr1.filter((x, i) => x !== arr1[i - 1]); console.log(JSON.stringify(res));