Как найти в массиве одинаковые элементы javascript

There are multiple methods available to check if an array contains duplicate values in JavaScript. You can use the indexOf() method, the Set object, or iteration to identify repeated items in an array.

Set Object

Set is a special data structure introduced in ES6 that stores a collection of unique values. Since each value in a Set has to be unique, passing any duplicate item will be removed automatically:

const numbers = [1, 2, 3, 2, 4, 5, 5, 6];

const unique = Array.from(new Set(numbers));

console.log(unique);
// [ 1, 2, 3, 4, 5, 6 ]

The Array.from() method, we used above, converts the Set back to an array. This is required because a Set is not an array. You could also use spread operator if you want for conversion:

const unique = [...new Set(numbers)];

To check if there were duplicate items in the original array, just compare the length of both arrays:

const numbers = [1, 2, 3, 2, 4, 5, 5, 6];

const unique = Array.from(new Set(numbers));

if(numbers.length === unique.length) {
    console.log(`Array doesn't contain duplicates.`);
} else {
    console.log(`Array contains duplicates.`);
}
// Output: Array contains duplicates.

To find out exactly which elements are duplicates, you could make use of the unique array above, and remove each item from the original array as shown below:

const numbers = [1, 2, 3, 2, 4, 5, 5, 6];

const set = new Set(numbers);

const duplicates = numbers.filter(item => {
    if (set.has(item)) {
        set.delete(item);
    } else {
        return item;
    }
});

console.log(duplicates);
// [ 2, 5 ]

indexOf() Method

In this method, we compare the index of the first occurrence of an element with all the elements in an array. If they do not match, it implies that the element is a duplicate:

const numbers = [1, 2, 3, 2, 4, 5, 5, 6];

const duplicates = numbers.filter((item, index) => index !== numbers.indexOf(item));

console.log(duplicates);
// [ 2, 5 ]

The above solution works perfectly as long as you only want to check if the array contains repeated items. However, the output array may contain duplicate items if those items occur more than twice in the array:

const numbers = [1, 2, 3, 2, 2, 4, 5, 5, 6];

const duplicates = numbers.filter((item, index) => index !== numbers.indexOf(item));

console.log(duplicates);
// [ 2, 2, 5 ]

some() Method

In JavaScript, the some() method returns true if one or more elements pass a certain condition.

Just like the filter() method, the some() method iterates over all elements in an array to evaluate the given condition.

In the callback function, we again use the indexOf() method to compare the current element index with other elements in the array. If both the indexes are the same, it means that the current item is not duplicate:

const numbers = [1, 2, 3, 2, 4, 5, 5, 6];

const isDuplicate = numbers.some((item, index) => index !== numbers.indexOf(item));

if (!isDuplicate) {
    console.log(`Array doesn't contain duplicates.`);
} else {
    console.log(`Array contains duplicates.`);
}
// Output: Array contains duplicates.

for Loop

Finally, the last method to find duplicates in an array is to use the for loop.

Here is an example that compares each element of the array with all other elements of the array to check if two values are the same using nested for loop:

const numbers = [1, 2, 3, 2, 4, 5, 5, 6];

let isDuplicate = false;

// Outer for loop
for (let i = 0; i < numbers.length; i++) {
    // Inner for loop
    for (let j = 0; j < numbers.length; j++) {
        // Skip self comparison
        if (i !== j) {
            // Check for duplicate
            if (numbers[i] === numbers[j]) {
                isDuplicate = true;
                // Terminate inner loop
                break;
            }
        }
        // Terminate outer loop
        if (isDuplicate) {
            break;
        }
    }
}

if (!isDuplicate) {
    console.log(`Array doesn't contain duplicates.`);
} else {
    console.log(`Array contains duplicates.`);
}
// Output: Array contains duplicates.

✌️ Like this article? Follow me on
Twitter
and LinkedIn.
You can also subscribe to
RSS Feed.

В этом посте мы обсудим, как найти все дубликаты в массиве в JavaScript.

1. Использование Array.prototype.indexOf() функция

Идея состоит в том, чтобы сравнить индекс всех элементов в массиве с индексом их первого появления. Если оба индекса не совпадают ни для одного элемента в массиве, можно сказать, что текущий элемент дублируется. Чтобы вернуть новый массив с дубликатами, используйте filter() метод.

В следующем примере кода показано, как реализовать это с помощью indexOf() метод:

const arr = [ 5, 3, 4, 2, 3, 7, 5, 6 ];

const findDuplicates = arr => arr.filter((item, index) => arr.indexOf(item) !== index)

const duplicates = findDuplicates(arr);

console.log(duplicates);

/*

    результат: [ 3, 5 ]

*/

Скачать  Выполнить код

 
Приведенное выше решение может привести к дублированию значений на выходе. Чтобы справиться с этим, вы можете преобразовать результат в Set, в котором хранятся уникальные значения.

function findDuplicates(arr) {

    const filtered = arr.filter((item, index) => arr.indexOf(item) !== index);

    return [...new Set(filtered)]

}

const arr = [ 5, 3, 4, 2, 3, 7, 5, 6 ];

const duplicates = findDuplicates(arr);

console.log(duplicates);

/*

    результат: [ 3, 5 ]

*/

Скачать  Выполнить код

2. Использование Set.prototype.has() функция

Кроме того, для повышения производительности вы можете использовать ES6. Установить структуру данных для эффективной фильтрации массива.

Следующее решение находит и возвращает дубликаты, используя has() метод. Это работает, потому что каждое значение в наборе должно быть уникальным.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

function findDuplicates(arr) {

    const distinct = new Set(arr);        // для повышения производительности

    const filtered = arr.filter(item => {

        // удаляем элемент из набора при первой же встрече

        if (distinct.has(item)) {

            distinct.delete(item);

        }

        // возвращаем элемент при последующих встречах

        else {

            return item;

        }

    });

    return [...new Set(filtered)]

}

const arr = [ 5, 3, 4, 2, 3, 7, 5, 6 ];

const duplicates = findDuplicates(arr);

console.log(duplicates);

/*

    результат: [ 3, 5 ]

*/

Скачать  Выполнить код

Это все о поиске всех дубликатов в массиве в JavaScript.

Спасибо за чтение.

Пожалуйста, используйте наш онлайн-компилятор размещать код в комментариях, используя C, C++, Java, Python, JavaScript, C#, PHP и многие другие популярные языки программирования.

Как мы? Порекомендуйте нас своим друзьям и помогите нам расти. Удачного кодирования 🙂

Another approach (also for object/array elements within the array1) could be2:

function chkDuplicates(arr,justCheck){
  var len = arr.length, tmp = {}, arrtmp = arr.slice(), dupes = [];
  arrtmp.sort();
  while(len--){
   var val = arrtmp[len];
   if (/nul|nan|infini/i.test(String(val))){
     val = String(val);
    }
    if (tmp[JSON.stringify(val)]){
       if (justCheck) {return true;}
       dupes.push(val);
    }
    tmp[JSON.stringify(val)] = true;
  }
  return justCheck ? false : dupes.length ? dupes : null;
}
//usages
chkDuplicates([1,2,3,4,5],true);                           //=> false
chkDuplicates([1,2,3,4,5,9,10,5,1,2],true);                //=> true
chkDuplicates([{a:1,b:2},1,2,3,4,{a:1,b:2},[1,2,3]],true); //=> true
chkDuplicates([null,1,2,3,4,{a:1,b:2},NaN],true);          //=> false
chkDuplicates([1,2,3,4,5,1,2]);                            //=> [1,2]
chkDuplicates([1,2,3,4,5]);                                //=> null

See also…

1 needs a browser that supports JSON, or a JSON library if not.
2 edit: function can now be used for simple check or to return an array of duplicate values

Для нахождения одинаковых элементов можно использовать следующий алгоритм:

  1. Находим количество вхождений (сколько раз встречается в списке) для каждого элемента
  2. Выводим только те, у которых количество вхождений больше 1

Алгоритм можно реализовать с помощью цикла:

const numbers = [4, 3, 3, 1, 15, 7, 4, 19, 19]; // исходный массив

const countItems = {}; // здесь будет храниться промежуточный результат

// получаем объект в котором ключ - это элемент массива, а значение - сколько раз встречается элемент в списке
// например так будет выглядеть этот объект после цикла:
// {1: 1, 3: 2, 4: 2, 7: 1, 15: 1, 19: 2}
// 1 встречается в тексте 1 раз, 2 встречается 2 раза, 4 встречается 2 раза и так далее
for (const item of numbers) {
  // если элемент уже был, то прибавляем 1, если нет - устанавливаем 1
  countItems[item] = countItems[item] ? countItems[item] + 1 : 1;
}

// обрабатываем ключи объекта, отфильтровываем все, что меньше 1
const result = Object.keys(countItems).filter((item) => countItems[item] > 1);
console.dir(result); // => ['3', '4', '19']

To know if simple array has duplicates we can compare first and last indexes of the same value:

The function:

var hasDupsSimple = function(array) {

    return array.some(function(value) {                            // .some will break as soon as duplicate found (no need to itterate over all array)
       return array.indexOf(value) !== array.lastIndexOf(value);   // comparing first and last indexes of the same value
    })
}

Tests:

hasDupsSimple([1,2,3,4,2,7])
// => true

hasDupsSimple([1,2,3,4,8,7])
// => false

hasDupsSimple([1,"hello",3,"bye","hello",7])
// => true

For an array of objects we need to convert the objects values to a simple array first:

Converting array of objects to the simple array with map:

var hasDupsObjects = function(array) {

  return array.map(function(value) {
    return value.suit + value.rank

  }).some(function(value, index, array) { 
       return array.indexOf(value) !== array.lastIndexOf(value);  
     })
}

Tests:

var cardHand = [
  { "suit":"spades", "rank":"ten" },
  { "suit":"diamonds", "rank":"ace" },
  { "suit":"hearts", "rank":"ten" },
  { "suit":"clubs", "rank":"two" },
  { "suit":"spades", "rank":"three" },
]

hasDupsObjects(cardHand);
// => false

var cardHand2 = [
  { "suit":"spades", "rank":"ten" },
  { "suit":"diamonds", "rank":"ace" },
  { "suit":"hearts", "rank":"ten" },
  { "suit":"clubs", "rank":"two" },
  { "suit":"spades", "rank":"ten" },
]

hasDupsObjects(cardHand2);
// => true

Добавить комментарий