How to remove repeated entries from an array while preserving non-consecutive duplicates?

前端 未结 5 1925
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-06 19:35

I have an array like var arr = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4, 5, 5, 5]; I really want the output to be [5,2,9,4,5]. My logic for this was:

5条回答
  •  误落风尘
    2020-12-06 19:40

    A bit hackey, but, hell, I like it.

    var arr = [5, 5, 5, 2, 2, 2, 2, 2, 9, 4, 5, 5, 5];
    var arr2 = arr.join().replace(/(.),(?=\1)/g, '').split(',');
    

    Gives you

    [5,2,9,4,5]
    

    Admittedly this will fall down if you're using sub-strings of more than one character, but as long as that's not the case, this should work fine.

提交回复
热议问题