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

Naturally, my approach was to loop through the first array once and check the index of each value in the second array. If the index is > -1, then push it onto the returned array.

​Array.prototype.diff = function(arr2) {
    var ret = [];
    for(var i in this) {   
        if(arr2.indexOf(this[i]) > -1){
            ret.push(this[i]);
        }
    }
    return ret;
};


My solution doesn’t use two loops like others do so it may run a bit faster. If you want to avoid using for..in, you can sort both arrays first to reindex all their values:

Array.prototype.diff = function(arr2) {
    var ret = [];
    this.sort();
    arr2.sort();
    for(var i = 0; i < this.length; i += 1) {
        if(arr2.indexOf(this[i]) > -1){
            ret.push(this[i]);
        }
    }
    return ret;
};

Usage would look like:

var array1 = ["cat", "sum","fun", "run", "hut"];
var array2 = ["bat", "cat","dog","sun", "hut", "gut"];

console.log(array1.diff(array2));

If you have an issue/problem with extending the Array prototype, you could easily change this to a function.

var diff = function(arr, arr2) {

And you’d change anywhere where the func originally said this to arr2.

Эффективнее пользоваться встроенными в голову мозгами, при наличии.

Можно ручками написать слияние:

let one = ['one', 'two', 'three', 'four', 'five'];
let two = ['a', 'b', 'five', 'c', 'one'];
one.sort();
two.sort();
let i = one.length, j = two.length, three = [];
while (i > 0 && j > 0) {
    i--;
    j--;
    if (one[i] > two[j]) j++;
    else if (one[i] < two[j]) i++;
    else three.push(one[i]);
}
console.log(three);

Можно воспользоваться библиотекой:

const _ = require("lodash");
console.log(_.intersection(one, two));

Можно воспользоваться встроенным классом Set (пусть будет задание на дом).

ps Developer, увидишь Кнута — передавай привет.

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 и многие другие популярные языки программирования.

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

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

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

Понравилась статья? Поделить с друзьями:
  • Как найти мужчину если у тебя ребенок
  • Как в 1с составить отчет по отпускам
  • Как найти расстояние вектора на функции
  • Как найти допустимую нагрузку
  • Как исправить царапины на порошковой краске