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?
我有两个数组,我希望能够比较这两个数组,只返回匹配的值。例如,两个数组都有值cat,因此将返回值cat。我还没有找到这样的东西。返回相似点的最佳方法是什么?
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
11 个解决方案
#1
34
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:
我的解决方案不像其他人那样使用两个循环,所以它可能运行得更快一些。如果你想避免使用…在这里,您可以首先对两个数组进行排序,以重新索引它们的所有值:
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
.
你可以在func最初对arr2说的任何地方改变。
#2
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 log(n) + m log(m))中运行,与O(n*m)(在其他解决方案中使用循环/索引)相比较,如果您处理的是大量的值,那么这个函数是有用的。
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"]
#3
8
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));
#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
3
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这样的库有一个叫做交集的实用方法来查找传入数组中的匹配项。看看:http://underscorejs.org/#交集
#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 array
loop 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
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;
#10
0
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'];
#11
0
Iterate on array1 and find the indexof element present in array2.
迭代array1并找到array2中存在的索引元素。
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)
#1
34
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:
我的解决方案不像其他人那样使用两个循环,所以它可能运行得更快一些。如果你想避免使用…在这里,您可以首先对两个数组进行排序,以重新索引它们的所有值:
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
.
你可以在func最初对arr2说的任何地方改变。
#2
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 log(n) + m log(m))中运行,与O(n*m)(在其他解决方案中使用循环/索引)相比较,如果您处理的是大量的值,那么这个函数是有用的。
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"]
#3
8
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));
#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
3
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这样的库有一个叫做交集的实用方法来查找传入数组中的匹配项。看看:http://underscorejs.org/#交集
#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 array
loop 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
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;
#10
0
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'];
#11
0
Iterate on array1 and find the indexof element present in array2.
迭代array1并找到array2中存在的索引元素。
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)