如何在两个数组中找到匹配值?

时间:2021-11-14 12:02:45

I have two arrays, and I want to be able to compare the two and only return the values that match. For example both arrays have the value cat so that is what will be returned. I haven't found anything like this. What would be the best way to return similarities?

我有两个数组,我希望能够比较两个数组,只返回匹配的值。例如,两个数组都具有值c​​at,因此将返回该值。我还没有找到这样的东西。返回相似之处的最佳方法是什么?

var array1 = ["cat", "sum","fun", "run"];var array2 = ["bat", "cat","dog","sun", "hut", "gut"];if array1 value is equal to array2 value then return match: cat

12 个解决方案

#1


38  

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.

当然,我的方法是循环遍历第一个数组并检查第二个数组中每个值的索引。如果索引> -1,则将其推送到返回的数组。

​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:

我的解决方案不会像其他人那样使用两个循环,因此可能运行得更快一些。如果要避免使用for..in,可以先对两个数组进行排序,以重新索引其所有值:

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.

如果您在扩展Array原型时遇到问题,可以轻松将其更改为函数。

var diff = function(arr, arr2) {

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

并且你会改变func最初说这个到arr2的地方。

#2


23  

As @hanu mentioned you could use lodash but you can also use native javascript with:

正如@hanu所提到的,你可以使用lodash,但你也可以使用原生的javascript:

const intersection = array1.filter(element => array2.includes(element));

#3


10  

This function runs in O(n log(n) + m log(m)) compared to O(n*m) (as seen in the other solutions with loops/indexOf) which can be useful if you are dealing with lots of values.

与O(n * m)相比,此函数在O(n log(n)+ m log(m))中运行(如使用loops / indexOf的其他解决方案中所示),如果处理大量值,这可能很有用。

However, because neither "a" > 1 nor "a" < 1, this only works for elements of the same type.

但是,因为既不是“a”> 1也不是“a”<1,这只适用于相同类型的元素。

function intersect_arrays(a, b) {    var sorted_a = a.concat().sort();    var sorted_b = b.concat().sort();    var common = [];    var a_i = 0;    var b_i = 0;    while (a_i < a.length           && b_i < b.length)    {        if (sorted_a[a_i] === sorted_b[b_i]) {            common.push(sorted_a[a_i]);            a_i++;            b_i++;        }        else if(sorted_a[a_i] < sorted_b[b_i]) {            a_i++;        }        else {            b_i++;        }    }    return common;}

Example:

var array1 = ["cat", "sum", "fun", "hut"], //modified for additional match    array2 = ["bat", "cat", "dog", "sun", "hut", "gut"];intersect_arrays(array1, array2);>> ["cat", "hut"]

#4


7  

Loop through the second array each time you iterate over an element in the first array, then check for matches.

每次迭代第一个数组中的元素时,循环遍历第二个数组,然后检查匹配。

var array1 = ["cat", "sum", "fun", "run"],    array2 = ["bat", "cat", "dog", "sun", "hut", "gut"];function getMatch(a, b) {    var matches = [];    for ( var i = 0; i < a.length; i++ ) {        for ( var e = 0; e < b.length; e++ ) {            if ( a[i] === b[e] ) matches.push( a[i] );        }    }    return matches;}getMatch(array1, array2); // ["cat"]

#5


7  

I found a slight alteration on what @jota3 suggested worked perfectly for me.

我发现@ jota3建议对我来说很有效。

var intersections = array1.filter(e => array2.indexOf(e) !== -1);

Hope this helps!

希望这可以帮助!

#6


2  

Libraries like underscore and lodash have a utility method called intersection to find matches in arrays passed in. Take a look at: http://underscorejs.org/#intersection

像下划线和lodash这样的库有一个名为intersection的实用方法,用于查找传入的数组中的匹配项。请查看:http://underscorejs.org/#intersection

#7


1  

Done as a answer so I can do formatting...

作为答案完成,所以我可以做格式化...

This is the the process you need to go through. Looping through an array for the specifics.

这是您需要经历的过程。通过数组循环显示细节。

create an empty arrayloop through array1, element by element. {  loop through array2, element by element {    if array1.element == array2.element {      add to your new array    }  }}

#8


1  

use lodash GLOBAL.utils    = require('lodash')var arr1 = ['first' , 'second'];var arr2 = ['second '];var result = utils.difference (arr1 , arr2);    console.log ( "result :" + result );

#9


1  

With some ES6:

有些ES6:

let sortedArray = [];firstArr.map((first) => {  sortedArray[defaultArray.findIndex(def => def === first)] = first;});sortedArray = sortedArray.filter(v => v);

This snippet also sorts the firstArr based on the order of the defaultArray

此代码段还会根据defaultArray的顺序对firstArr进行排序

like:

let firstArr = ['apple', 'kiwi', 'banana'];let defaultArray = ['kiwi', 'apple', 'pear'];...console.log(sortedArray);// ['kiwi', 'apple'];

#10


0  

If your values are non-null strings or numbers, you can use an object as a dictionary:

如果您的值是非空字符串或数字,则可以将对象用作字典:

var map = {}, result = [], i;for (i = 0; i < array1.length; ++i) {    map[array1[i]] = 1;}for (i = 0; i < array2.length; ++i) {    if (map[array2[i]] === 1) {        result.push(array2[i]);        // avoid returning a value twice if it appears twice in array 2        map[array2[i]] = 0;    }}return result;

#11


0  

Iterate on array1 and find the indexof element present in array2.

迭代array1并找到array2中存在的indexof元素。

var array1 = ["cat", "sum","fun", "run"];var array2 = ["bat", "cat","sun", "hut", "gut"];var str='';for(var i=0;i<array1.length;i++){        if(array2.indexOf(array1[i]) != -1){           str+=array1[i]+' ';       };    }console.log(str)

#12


0  

var array1  = [1, 2, 3, 4, 5, 6],var array2 = [1, 2, 3, 4, 5, 6, 7, 8, 9];var array3 = array2.filter(function(obj) {     return array1.indexOf(obj) == -1; });

#1


38  

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.

当然,我的方法是循环遍历第一个数组并检查第二个数组中每个值的索引。如果索引> -1,则将其推送到返回的数组。

​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:

我的解决方案不会像其他人那样使用两个循环,因此可能运行得更快一些。如果要避免使用for..in,可以先对两个数组进行排序,以重新索引其所有值:

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.

如果您在扩展Array原型时遇到问题,可以轻松将其更改为函数。

var diff = function(arr, arr2) {

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

并且你会改变func最初说这个到arr2的地方。

#2


23  

As @hanu mentioned you could use lodash but you can also use native javascript with:

正如@hanu所提到的,你可以使用lodash,但你也可以使用原生的javascript:

const intersection = array1.filter(element => array2.includes(element));

#3


10  

This function runs in O(n log(n) + m log(m)) compared to O(n*m) (as seen in the other solutions with loops/indexOf) which can be useful if you are dealing with lots of values.

与O(n * m)相比,此函数在O(n log(n)+ m log(m))中运行(如使用loops / indexOf的其他解决方案中所示),如果处理大量值,这可能很有用。

However, because neither "a" > 1 nor "a" < 1, this only works for elements of the same type.

但是,因为既不是“a”> 1也不是“a”<1,这只适用于相同类型的元素。

function intersect_arrays(a, b) {    var sorted_a = a.concat().sort();    var sorted_b = b.concat().sort();    var common = [];    var a_i = 0;    var b_i = 0;    while (a_i < a.length           && b_i < b.length)    {        if (sorted_a[a_i] === sorted_b[b_i]) {            common.push(sorted_a[a_i]);            a_i++;            b_i++;        }        else if(sorted_a[a_i] < sorted_b[b_i]) {            a_i++;        }        else {            b_i++;        }    }    return common;}

Example:

var array1 = ["cat", "sum", "fun", "hut"], //modified for additional match    array2 = ["bat", "cat", "dog", "sun", "hut", "gut"];intersect_arrays(array1, array2);>> ["cat", "hut"]

#4


7  

Loop through the second array each time you iterate over an element in the first array, then check for matches.

每次迭代第一个数组中的元素时,循环遍历第二个数组,然后检查匹配。

var array1 = ["cat", "sum", "fun", "run"],    array2 = ["bat", "cat", "dog", "sun", "hut", "gut"];function getMatch(a, b) {    var matches = [];    for ( var i = 0; i < a.length; i++ ) {        for ( var e = 0; e < b.length; e++ ) {            if ( a[i] === b[e] ) matches.push( a[i] );        }    }    return matches;}getMatch(array1, array2); // ["cat"]

#5


7  

I found a slight alteration on what @jota3 suggested worked perfectly for me.

我发现@ jota3建议对我来说很有效。

var intersections = array1.filter(e => array2.indexOf(e) !== -1);

Hope this helps!

希望这可以帮助!

#6


2  

Libraries like underscore and lodash have a utility method called intersection to find matches in arrays passed in. Take a look at: http://underscorejs.org/#intersection

像下划线和lodash这样的库有一个名为intersection的实用方法,用于查找传入的数组中的匹配项。请查看:http://underscorejs.org/#intersection

#7


1  

Done as a answer so I can do formatting...

作为答案完成,所以我可以做格式化...

This is the the process you need to go through. Looping through an array for the specifics.

这是您需要经历的过程。通过数组循环显示细节。

create an empty arrayloop through array1, element by element. {  loop through array2, element by element {    if array1.element == array2.element {      add to your new array    }  }}

#8


1  

use lodash GLOBAL.utils    = require('lodash')var arr1 = ['first' , 'second'];var arr2 = ['second '];var result = utils.difference (arr1 , arr2);    console.log ( "result :" + result );

#9


1  

With some ES6:

有些ES6:

let sortedArray = [];firstArr.map((first) => {  sortedArray[defaultArray.findIndex(def => def === first)] = first;});sortedArray = sortedArray.filter(v => v);

This snippet also sorts the firstArr based on the order of the defaultArray

此代码段还会根据defaultArray的顺序对firstArr进行排序

like:

let firstArr = ['apple', 'kiwi', 'banana'];let defaultArray = ['kiwi', 'apple', 'pear'];...console.log(sortedArray);// ['kiwi', 'apple'];

#10


0  

If your values are non-null strings or numbers, you can use an object as a dictionary:

如果您的值是非空字符串或数字,则可以将对象用作字典:

var map = {}, result = [], i;for (i = 0; i < array1.length; ++i) {    map[array1[i]] = 1;}for (i = 0; i < array2.length; ++i) {    if (map[array2[i]] === 1) {        result.push(array2[i]);        // avoid returning a value twice if it appears twice in array 2        map[array2[i]] = 0;    }}return result;

#11


0  

Iterate on array1 and find the indexof element present in array2.

迭代array1并找到array2中存在的indexof元素。

var array1 = ["cat", "sum","fun", "run"];var array2 = ["bat", "cat","sun", "hut", "gut"];var str='';for(var i=0;i<array1.length;i++){        if(array2.indexOf(array1[i]) != -1){           str+=array1[i]+' ';       };    }console.log(str)

#12


0  

var array1  = [1, 2, 3, 4, 5, 6],var array2 = [1, 2, 3, 4, 5, 6, 7, 8, 9];var array3 = array2.filter(function(obj) {     return array1.indexOf(obj) == -1; });