Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array

后端 未结 30 3305
再見小時候
再見小時候 2020-11-21 04:35

I need to check a JavaScript array to see if there are any duplicate values. What\'s the easiest way to do this? I just need to find what the duplicated values are - I don\'

30条回答
  •  忘掉有多难
    2020-11-21 05:18

    Find duplicate values in an array

    This should be one of the shortest ways to actually find duplicate values in an array. As specifically asked for by the OP, this does not remove duplicates but finds them.

    var input = [1, 2, 3, 1, 3, 1];
    
    var duplicates = input.reduce(function(acc, el, i, arr) {
      if (arr.indexOf(el) !== i && acc.indexOf(el) < 0) acc.push(el); return acc;
    }, []);
    
    document.write(duplicates); // = 1,3 (actual array == [1, 3])

    This doesn't need sorting or any third party framework. It also doesn't need manual loops. It works with every value indexOf() (or to be clearer: the strict comparision operator) supports.

    Because of reduce() and indexOf() it needs at least IE 9.

提交回复
热议问题