Who can help to explain this JavaScript algorithm [].filter.call()

前端 未结 7 999
情深已故
情深已故 2021-01-22 03:41

I have task to receive unique element in order from string as parameter. I do not understand how this function uniqueElements returns [\'A\',\'B\',\'C\',\'B\']

7条回答
  •  南笙
    南笙 (楼主)
    2021-01-22 04:07

    I would do this O(n) time by utilizing Array.prototype.reduce() as follows;

    var str = "AAAABBBBCCBB",
    uniques = Array.prototype.reduce.call(str, (p,c,i) => i-1 ? p[p.length-1] !== c ? (p.push(c),p)
                                                                                    : p
                                                              : [c]);
    console.log(uniques);

提交回复
热议问题