Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Translating Python loop to Javascript

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]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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));
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading