Как найти повторы в массиве js

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

В этом посте мы обсудим, как найти все дубликаты в массиве в 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 и многие другие популярные языки программирования.

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

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.

If your array nests other arrays/objects, using the Set approach may not be what you want since comparing two objects compares their references. If you want to check that their contained values are equal, something else is needed. Here are a couple different approaches.

Approach 1: Map using JSON.stringify for keys

If you want to consider objects with the same contained values as equal, here’s one simple way to do it using a Map object. It uses JSON.stringify to make a unique id for each element in the array.

I believe the runtime of this would be O(n * m) on arrays, assuming JSON.stringify serializes in linear time. n is the length of the outer array, m is size of the arrays. If the objects get very large, however, this may slow down since the keys will be very long. Not a very space-efficient implementation, but it is simple and works for many data types.

function checkArrayDupeFree(myArray, idFunc) {
    const dupeMap = new Map();
    for (const el of myArray) {
        const id = idFunc(el);
        if (dupeMap.has(id))
            return false;
        dupeMap.set(id, el);
    }
    return true;
}

const notUnique = [ [1, 2], [1, 3], [1, 2] ];
console.log(`${JSON.stringify(notUnique)} has no duplicates? ${checkArrayDupeFree(notUnique, JSON.stringify)}`);

const unique = [ [2, 1], [1, 3], [1, 2] ];
console.log(`${JSON.stringify(unique)} has no duplicates? ${checkArrayDupeFree(unique, JSON.stringify)}`);

Of course, you could also write your own id-generator function, though I’m not sure you can do much better than JSON.stringify.

Approach 2: Custom HashMap, Hashcode, and Equality implementations

If you have a lot of big arrays, it may be better performance-wise to implement your own hash/equality functions and use a Map as a HashMap.

In the following implementation, we hash the array. If there is a collision, map a key to an array of collided values, and check to see if any of the array values match according to the equality function.

The downside of this approach is that you may have to consider a wide range of types for which to make hashcode/equality functions, depending on what’s in the array.

function checkArrayDupeFreeWHashes(myArray, hashFunc, eqFunc) {
    const hashMap = new Map();
    
    for (const el of myArray) {
        const hash = hashFunc(el);
        const hit = hashMap.get(hash);
    
        if (hit == null)
            hashMap.set(hash, [el]);
        else if (hit.some(v => eqFunc(v, el)))
            return false;
        else
            hit.push(el);
    }

    return true;
}

Here’s a demo of the custom HashMap in action. I implemented a hashing function and an equality function for arrays of arrays.

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

  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']

Понравилась статья? Поделить с друзьями:

Не пропустите также:

  • Как найти больше подписчиков в инстаграм
  • Как найти интенданта черного клинка
  • Ошибка при проверке подлинности pppoe или pppoe как исправить
  • Как найти по ip адрес путь
  • Как исправить текст в отправленном письме

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии