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
.
Как найти пересечение между двумя массивами JavaScript?
У нас есть два массива с уникальными наборами чисел:
let arr1 = [1,2,3,4,5,6]; let arr2 = [4,5,6,7,8,9];
В каждом массиве число встречается ровно 1 раз.
Мы хотим получить такие числа, которые есть и в первом массиве и во втором. Как это сделать?
Получение массива повторяющихся чисел из двух массивов при помощи двух циклов FOR OF в JavaScript
Мы можем написать свою функцию, которая будет принимать два параметра — два массива.
function intersect(a, b){ let new_arr = []; for(element_a of a){ for(element_b of b){ if(element_b == element_a){new_arr.push(element_a)}} } return new_arr; };
Цикл FOR OF обегает значения в свойствах объектов. В нашем случаем массивы — это объекты класса Array по стандарту ECMAScript. Именно в этой функции нас не интересует цикл FOR или FOR IN.
Мы назвали нашу функцию именем «intersect» по аналогии с названием оператора в языке SQL.
Пример работы функции по нахождению повторяющихся чисел в двух массивах
Вызываем нашу функцию:
intersect(arr1, arr2)
Результат работы функции по массивам из чисел:
Результатом вызова нашей функции стал массив из чисел (класс Number). Каждый элемент нового массива присутствует как в первом массиве, так и во втором.
Данная функция также хорошо будет работать и с массивами из строк.
let arr3 = ['1','2','3','4','5','6']; let arr4 = ['4','5','6','7','8','9'];
В каждом массиве строка встречается ровно 1 раз.
Вызываем нашу функцию:
intersect(arr3, arr4)
Результат работы функции по массивам из строк:
Информационные ссылки
Официальная страница стандарта ECMAScript — https://tc39.es/ecma262/multipage/ — https://tc39.es/ecma262/
Объекты Array — https://tc39.es/ecma262/#sec-array-objects
Цикл FOR OF — https://tc39.es/ecma262/#sec-for-in-and-for-of-statements
Версия стандарта от 06 августа 2020 г. Принимать участие: GitHub whatwg / fetch (новый выпуск, открытые выпуски) IRC: #whatwg на Freenode Фиксации: […]
Оператор return относится к операторам «внезапного завершения» функции. Это значит, что кроме return существуют другие операторы, которые могут внезапно завершить выполнение функции. […]
Синтаксис условного оператора ConditionalExpression [In, Yield, Await] : ShortCircuitExpression [?In, ?Yield, ?Await] ShortCircuitExpression [?In, ?Yield, ?Await] ? AssignmentExpression [+In, ?Yield, ?Await] : AssignmentExpression [?In, ?Yield, ?Await] […]
Есть массив: var massiv = [ [1, 2, 3], [2, 888, 999], [3, 0, 0], [4, 55, 66] ] В этом […]
(PHP 4 >= 4.0.1, PHP 5, PHP 7, PHP 8)
array_intersect — Вычисляет схождение массивов
Описание
array_intersect(array $array
, array ...$arrays
): array
Список параметров
-
array
-
Основной проверяемый массив
-
arrays
-
Массивы, с которыми идёт сравнение значений
Возвращаемые значения
Возвращает массив, содержащий все значения array
,
которые существуют во всех переданных аргументах.
Список изменений
Версия | Описание |
---|---|
8.0.0 |
Функция теперь может быть вызвана только с одним параметром. Раньше требовалось не менее двух параметров. |
Примеры
Пример #1 Пример использования array_intersect()
<?php
$array1 = array("a" => "green", "red", "blue");
$array2 = array("b" => "green", "yellow", "red");
$result = array_intersect($array1, $array2);
print_r($result);
?>
Результат выполнения данного примера:
Array ( [a] => green [0] => red )
Примечания
Замечание:
Два элемента считаются одинаковыми тогда и только тогда, когда
(string) $elem1 === (string) $elem2
. Другими словами,
когда их строковые представления идентичны.
Смотрите также
- array_intersect_assoc() – Вычисляет схождение массивов с дополнительной проверкой индекса
- array_diff() – Вычислить расхождение массивов
- array_diff_assoc() – Вычисляет расхождение массивов с дополнительной проверкой индекса
stuart at horuskol dot co dot uk ¶
14 years ago
A clearer example of the key preservation of this function:
<?php
$array1
= array(2, 4, 6, 8, 10, 12);
$array2 = array(1, 2, 3, 4, 5, 6);var_dump(array_intersect($array1, $array2));
var_dump(array_intersect($array2, $array1));?>
yields the following:
array(3) {
[0]=> int(2)
[1]=> int(4)
[2]=> int(6)
}
array(3) {
[1]=> int(2)
[3]=> int(4)
[5]=> int(6)
}
This makes it important to remember which way round you passed the arrays to the function if these keys are relied on later in the script.
Niels ¶
16 years ago
Here is a array_union($a, $b):
<?php
// $a = 1 2 3 4
$union = // $b = 2 4 5 6
array_merge(
array_intersect($a, $b), // 2 4
array_diff($a, $b), // 1 3
array_diff($b, $a) // 5 6
); // $u = 1 2 3 4 5 6
?>
Shawn Pyle ¶
13 years ago
array_intersect handles duplicate items in arrays differently. If there are duplicates in the first array, all matching duplicates will be returned. If there are duplicates in any of the subsequent arrays they will not be returned.
<?php
array_intersect(array(1,2,2),array(1,2,3)); //=> array(1,2,2)
array_intersect(array(1,2,3),array(1,2,2)); //=> array(1,2)
?>
sapenov at gmail dot com ¶
17 years ago
If you need to supply arbitrary number of arguments
to array_intersect() or other array function,
use following function:
$full=call_user_func_array('array_intersect', $any_number_of_arrays_here);
blu at dotgeek dot org ¶
18 years ago
Note that array_intersect and array_unique doesnt work well with multidimensional arrays.
If you have, for example,
<?php
$orders_today
[0] = array('John Doe', 'PHP Book');
$orders_today[1] = array('Jack Smith', 'Coke');$orders_yesterday[0] = array('Miranda Jones', 'Digital Watch');
$orders_yesterday[1] = array('John Doe', 'PHP Book');
$orders_yesterday[2] = array('Z? da Silva', 'BMW Car');?>
and wants to know if the same person bought the same thing today and yesterday and use array_intersect($orders_today, $orders_yesterday) you'll get as result:
<?phpArray
(
[0] => Array
(
[0] => John Doe
[1] => PHP Book
)
[
1] => Array
(
[0] => Jack Smith
[1] => Coke
)
)
?>
but we can get around that by serializing the inner arrays:
<?php
$orders_today
[0] = serialize(array('John Doe', 'PHP Book'));
$orders_today[1] = serialize(array('Jack Smith', 'Coke'));$orders_yesterday[0] = serialize(array('Miranda Jones', 'Digital Watch'));
$orders_yesterday[1] = serialize(array('John Doe', 'PHP Book'));
$orders_yesterday[2] = serialize(array('Z? da Silva', 'Uncle Tungsten'));?>
so that array_map("unserialize", array_intersect($orders_today, $orders_yesterday)) will return:
<?phpArray
(
[0] => Array
(
[0] => John Doe
[1] => PHP Book
)
)
?>
showing us who bought the same thing today and yesterday =)
[]s
yuval at visualdomains dot com ¶
8 years ago
Using isset to achieve this, is many times faster:
<?php
$m
= range(1,1000000);
$s = [2,4,6,8,10];// Use array_intersect to return all $m values that are also in $s
$tstart = microtime(true);
print_r (array_intersect($m,$s));
$tend = microtime(true);
$time = $tend - $tstart;
echo "Took $time";// Use array_flip and isset to return all $m values that are also in $s
$tstart = microtime(true);
$f = array_flip($s);
/* $f now looks like this:
(
[2] => 0
[4] => 1
[6] => 2
[8] => 3
[10] => 4
)
*/
// $u will hold the intersected values
$u = [];
foreach ($m as $v) {
if (isset($f[$v])) $u[] = $v;
}
print_r ($u);
$tend = microtime(true);
$time = $tend - $tstart;
echo "Took $time";
?>
Results:
Array
(
[1] => 2
[3] => 4
[5] => 6
[7] => 8
[9] => 10
)
Took 4.7170009613037
(
[0] => 2
[1] => 4
[2] => 6
[3] => 8
[4] => 10
)
Took 0.056024074554443
array_intersect: 4.717
array_flip+isset: 0.056
dml at nm dot ru ¶
12 years ago
The built-in function returns wrong result when input arrays have duplicate values.
Here is a code that works correctly:
<?php
function array_intersect_fixed($array1, $array2) {
$result = array();
foreach ($array1 as $val) {
if (($key = array_search($val, $array2, TRUE))!==false) {
$result[] = $val;
unset($array2[$key]);
}
}
return $result;
}
?>
matang dot dave at gmail dot com ¶
7 years ago
Take care of value types while using array_intersect function as there is no option for strict type check as in in_array function.
$array1 = array(true,2);
$array2 = array(1, 2, 3, 4, 5, 6);
var_dump(array_intersect($array1, $array2));
result is :
array(2) {
[0] => bool(true)
[1] => int(2)
}
info at iridsystem dot it ¶
7 years ago
This function is able to sort an array based on another array that contains the order of occurrence. The values that are not present will be transferred into the end of the resultant.
Questa funzione permette di ordinare i valori di un array ($tosort) basandosi sui valori contenuti in un secondo array ($base), i valori non trovati verranno posizionati alla fine dell'ordinamento senza un'ordine specifico.
<?
$base= array('one', 'two', 'three');
$tosort= array('a'=>'two', 'b'=>'three', 'c'=>'five', 'd'=>'one', 'and'=>'four', 'f'=>'one');
uasort($tosort, function($key1, $key2) use ($base) {
$a1=array_search($key1, $base);
$a2=array_search($key2, $base);
if ( $a1===false && $a2===false ) { return 0; }
else if ( $a1===false && $a2 !== false) { return 1; }
else if ( $a1!==false && $a2 === false) {return -1;}
if( $a1 > $a2 ) { return 1; }
else if ( $a1 < $a2 ) { return -1; }
else if ( $a1 == $a2 ) { return 0; }
});
var_dump($tosort);
/*
the resulting of $tosort
array
'd' => string 'one' (length=3)
'f' => string 'one' (length=3)
'a' => string 'two' (length=3)
'b' => string 'three' (length=3)
'c' => string 'five' (length=6)
'e' => string 'four' (length=7)
*/
Gabriel
?>
Esfandiar — e.bandari at gmail dot com ¶
14 years ago
Regarding array union: Here is a faster version array_union($a, $b)
But it is not needed! See below.
<?php
// $a = 1 2 3 4
$union = // $b = 2 4 5 6
array_merge(
$a,
array_diff($b, $a) // 5 6
); // $u = 1 2 3 4 5 6
?>
You get the same result with $a + $b.
N.B. for associative array the results of $a+$b and $b+$a are different, I think array_diff_key is used.
Cheers, E
theking at king dot ma ¶
1 year ago
I use array_intersect for a quick check of $_GET parameters;
<?php declare(strict_types=1)$_params = ['cust_id','prod_id'];
$_params_check = array_intersect(array_keys($_GET),$_params);
if(count($_params_check) !== count($_params)) {
header("HTTP/1.1 400 Bad Request");
die();
}
?>
the file will die with a 400 error if cust_id or prod_id or both are missing from $_GET. But i could be used on $_POST and $_REQUEST as well obviously.
Anonymous ¶
2 years ago
array_intersect use Value, not callback
array_uintersect use Value, callback receives Value
array_intersect_key use Key, not callback
array_intersect_ukey use Key, callback receives Key
array_intersect_assoc use Both, not callback
array_intersect_uassoc use Both, callback receives Key ONLY
array_uintersect_assoc use Both, callback receives Value ONLY
array_uintersect_uassoc use Both, One callback receives the Key, the other receives the Value.
Yohann ¶
13 years ago
I used array_intersect in order to sort an array arbitrarly:
<?php
$a = array('one', 'two', 'three', 'four', 'five', 'six', 'seven', 'height', 'nine', 'ten');
$b = array('four', 'one', 'height', 'five')
var_dump(array_intersect($a, $b);
?>
will output:
0 => 'one'
1 => 'four'
2 => 'five'
3 => 'height'
i hope this can help...
Oto Brglez ¶
14 years ago
If you wish to create intersection with arrays that are empty. Than the result of intersection is empty array.
If you wish to change this. I sugest that you do this.
It simply "ignores" empty arrays. Before loop use 1st array.
<?php
$a
= array();
$a[] = 1;
$a[] = 2;
$a[] = 3;$b = array();
$b[] = 4;
$b[] = 5;
$b[] = 1;$c = array();
$c[] = 1;
$c[] = 5;
$d = array();$kb=array('a','b','c','d');$out = $a;
foreach($kb as $k){
if(!empty(${$k})) $out = array_intersect($out,${$k});
};
print_r($out);
// The result is array
// The result is empty array
print_r(array_intersect($a,$b,$c,$d));?>
Malte ¶
15 years ago
Extending the posting by Terry from 07-Feb-2006 04:42:
If you want to use this function with arrays which have sometimes the same value several times, it won't be checked if they're existing in the second array as much as in the first.
So I delete the value in the second array, if it's found there:
<?php
$firstarray = array(1, 1, 2, 3, 4, 1);
$secondarray = array(4, 1, 6, 5, 4, 1);//array_intersect($firstarray, $secondarray): 1, 1, 1, 4foreach ($firstarray as $key=>$value){
if (!in_array($value,$secondarray)){
unset($firstarray[$key]);
}else{
unset($secondarray[array_search($value,$secondarray)]);
}
}//$firstarray: 1, 1, 4?>
nthitz at gmail dot com ¶
16 years ago
I did some trials and if you know the approximate size of the arrays then it would seem to be a lot faster to do this <?php array_intersect($smallerArray, $largerArray); ?> Where $smallerArray is the array with lesser items. I only tested this with long strings but I would imagine that it is somewhat universal.
t dot wiltzius at insightbb dot com ¶
18 years ago
I needed to compare an array with associative keys to an array that contained some of the keys to the associative array. Basically, I just wanted to return only a few of the entries in the original array, and the keys to the entries I wanted were stored in another array. This is pretty straightforward (although complicated to explain), but I couldn't find a good function for comparing values to keys. So I wrote this relatively straightforward one:
<?phpfunction key_values_intersect($values,$keys) {
foreach($keys AS $key) {
$key_val_int[$key] = $values[$key];
}
return $key_val_int;
}$big = array("first"=>2,"second"=>7,"third"=>3,"fourth"=>5);
$subset = array("first","third");print_r(key_values_intersect($big,$subset));?>
This will return:
Array ( [first] => 2 [third] => 3 )
anbolb at boltblue dot com ¶
19 years ago
This is also handy for testing an array for one of a series of acceptable elements. As a simple example, if you're expecting the query string to contain one of, say, user_id, order_id or item_id, to find out which one it is you could do this:
<?php
$valid_ids = array ('user_id', 'item_id', 'order_id');
if ($id = current (array_intersect ($valid_ids, array_keys ($_GET))))
{
// do some stuff with it
}
else
// error - invalid id passed, or none at all
?>
...which could be useful for constructing an SQL query, or some other situation where testing for them one by one might be too clumsy.
terry(-at-)shuttleworths(-dot-)net ¶
17 years ago
I couldn't get array_intersect to work with two arrays of identical objects, so I just did this:
foreach ($firstarray as $key=>$value){
if (!in_array($value,$secondarray)){
unset($firstarray[$key]);
}
}
This leaves $firstarray as the intersection.
Seems to work fine & reasonably quickly.
tom p ¶
17 years ago
If you store a string of keys in a database field and want to match them to a static array of values, this is a quick way to do it without loops:
<?
$vals = array("Blue","Green","Pink","Yellow");
$db_field = "0,2,3";
echo implode(", ", array_flip(array_intersect(array_flip($vals), explode(",", $db_field))));
// will output "Blue, Pink, Yellow"
?>
caffinated ¶
10 years ago
If you're looking for a relatively easy way to strictly intersect keys and values recursively without array key reordering, here's a simple recursive function:
<?php
function array_intersect_recursive($array1, $array2)
{
foreach($array1 as $key => $value)
{
if (!isset($array2[$key]))
{
unset($array1[$key]);
}
else
{
if (is_array($array1[$key]))
{
$array1[$key] = array_intersect_recursive($array1[$key], $array2[$key]);
}
elseif ($array2[$key] !== $value)
{
unset($array1[$key]);
}
}
}
return $array1;
}
?>
ben at kazez dot com ¶
19 years ago
To check whether an array $a is a subset of array $b, do the following:
<?php
if(array_unique($b + $a) === $b)
//...
?>
Actually, PHP ought to have a function that does this for you. But the above example works.
david at audiogalaxy dot com ¶
22 years ago
Note that array_intersect() considers the type of the array elements when it compares them.
If array_intersect() doesn't appear to be working, check your inputs using var_dump() to make sure you're not trying to intersect an array of integers with an array of strings.
gary ¶
13 years ago
i wrote this one to get over the problem i found in getting strings intersected instead of arrays as there is no function in php.
<?php
function matched_main_numbers($string, $string2)
{
$string = "04 16 17 20 29";
$arr1 = explode(" ", $string);
$string2 = "45 34 04 29 16";
$arr2 = explode(" ", $string2);
$array = array_intersect($arr1, $arr2);
$comma_separated = implode($array);
$str = $comma_separated;
$balls = "$comma_separated";
$matched_balls = chunk_split($balls,2," ");
$matched_balls =" $matched_balls";
$number_of_matched_main_balls = strlen($str);
$number_of_matched_main_balls = ($number_of_matched_main_balls/2);
$numbers = "You matched $number_of_matched_main_balls main balls";
return
$numbers;
}
?>
meihao at 126 dot com ¶
9 years ago
<?php
$a=array(1,2,'3',4);
$b=array('1',2,3);var_dump($a,$b);result:
array (size=3)
0 => int 1
1 => int 2
2 => string '3' (length=1)?>
Alessandro Ranellucci alex at primafila dot net ¶
19 years ago
array_intersect($array1, $array2);
returns the same as:
array_diff($array1, array_diff($array1, $array2));
Ehsan.Chavoshi.com ¶
3 years ago
I wrote this function to recursively replace array keys with array values (flip) and fill values with defined value. it can be used for recursive array intersect functions .
<?php
function array_values_to_keys_r($array, $fill_value = null)
{
$flipped = [];
foreach ($array as $key => $value) {
if (is_array($value)) {
$flipped [$key] = array_values_to_keys_r($value);
} else {
$flipped [$value] = $fill_value;
}
}
return $flipped;
}
?>
zoolyka at gmail dot com ¶
4 years ago
If you have to intersect arrays of unique values then using array_intersect_key is about 20 times faster, just have to flip the key value pairs of the arrays, then flip the result again.
<?php
$one
= range(1, 250000);
$two = range(50000, 150000);$start = microtime(true);$intersection = array_intersect($one, $two);
echo
"Did it in ".( microtime(true) - $start )." seconds.n";$start = microtime(true);$intersection = array_flip(array_intersect_key(array_flip($one), array_flip($two)));
echo
"Did it in ".( microtime(true) - $start )." seconds.n";?>
Did it in 0.89163708686829 seconds.
Did it in 0.038213968276978 seconds.
ram ¶
4 years ago
$x = array('ram@hb.in', 'ram', 'rams@hb.in');
$y = array('1231231231');
$result=array_intersect($x,$z);
$res = array_intersect($y, $z);
Mike Block ¶
10 years ago
I bench-marked some uses of array_intersect and can't believe how slow it is. This isn't as elaborate, but handles most cases and is much faster:
<?php
/**
examines two arrays and returns the intersected arrays with matching keys (ignores duplicate keys)
*/
function simple_array_intersect($a,$b) {
$a_assoc = $a != array_values($a);
$b_assoc = $b != array_values($b);
$ak = $a_assoc ? array_keys($a) : $a;
$bk = $b_assoc ? array_keys($b) : $b;
$out = array();
for ($i=0;$i<sizeof($ak);$i++) {
if (in_array($ak[$i],$bk)) {
if ($a_assoc) {
$out[$ak[$i]] = $a[$ak[$i]];
} else {
$out[] = $ak[$i];
}
}
}
return $out;
}?>
You can try this out with this:
<?php
// create a large array (simple)
$first = array();
for ($i=500;$i<500000;$i++) {
$first[] = $i;
}
// create a smaller array (associative)
$second = array();
for ($i=499990;$i<500000;$i++) {
$second[$i] = rand();
}
echo microtime(true)."n";
// built-in function
print_r(array_intersect($first,$second));
echo microtime(true)."n";
// favour simple array as match
print_r(simple_array_intersect($first,$second));
echo microtime(true)."n";
// favour associative keys for match
print_r(simple_array_intersect($second,$first));
echo microtime(true)."n";?>
karl at libsyn dot com ¶
14 years ago
Given a multidimensional array that represents AND/OR relationships (example below), you can use a recursive function with array_intersect() to see if another array matches that set of relationships.
For example: array( array( 'red' ), array( 'white', 'blue' ) ) represents "red OR ( white AND blue )". array( 'red', array( 'white', 'blue' ) ) would work, too, BTW.
If I have array( 'red' ) and I want to see if it matches the AND/OR array, I use the following function. It returns the matched array,
but can just return a boolean if that's all you need:
<?php
$needle = array( array( 'red' ), array( 'white', 'blue' ) );
$haystack = array( 'red' );
function
findMatchingArray( $needle, $haystack ) {
foreach( $needle as $element ) {
$test_element = (array) $element;
if( count( $test_element ) == count( array_intersect( $test_element, $haystack ) ) ) {
return $element;
}
}
return
false;
}
?>
Pretty tough to describe what I needed it to do, but it worked. I don't know if anyone else out there needs something like this, but hope this helps.
189780 at gmail dot com ¶
13 years ago
Actually array_intersect finds the dublicate values, here is my approach which is 5 times faster than built-in function array_intersect().. Give a try..
<?php
function my_array_intersect($a,$b)
{
for($i=0;$i<sizeof($a);$i++)
{
$m[]=$a[$i];
}
for($i=0;$i<sizeof($a);$i++)
{
$m[]=$b[$i];
}
sort($m);
$get=array();
for($i=0;$i<sizeof($m);$i++)
{
if($m[$i]==$m[$i+1])
$get[]=$m[$i];
}
return $get;
}
?>
Barış ÇUHADAR
189780@gmail.com
jake ¶
6 years ago
Also note that, even without the availability of the strict mode switch, false does not match 0:
array_intersect([false], [0]) == [];
Even in PHP 7.1
В этом посте мы обсудим, как найти все дубликаты в массиве в 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 и многие другие популярные языки программирования.
Как мы? Порекомендуйте нас своим друзьям и помогите нам расти. Удачного кодирования 🙂