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

后端 未结 30 3260
再見小時候
再見小時候 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:34

    Using "includes" to test if the element already exists.

    var arr = [1, 1, 4, 5, 5], darr = [], duplicates = [];
    
    for(var i = 0; i < arr.length; i++){
      if(darr.includes(arr[i]) && !duplicates.includes(arr[i]))
        duplicates.push(arr[i])
      else
        darr.push(arr[i]);
    }
    
    console.log(duplicates);

    Array with duplicates

    [1, 1, 4, 5, 5]

    Array with distinct elements

    [1, 4, 5]

    duplicate values are

    [1, 5]

提交回复
热议问题