javascript 在javascript中返回两个字符串数组差异的函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11704509/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 14:04:23  来源:igfitidea点击:

Function that returns difference of two arrays of strings in javascript

javascriptjquery

提问by oneiros

Possible Duplicate:
What is the fastest or most elegant way to compute a set difference using Javascript arrays?

可能的重复:
使用 Javascript 数组计算集差的最快或最优雅的方法是什么?

I need help with devising a function that will return the difference between two arrays of strings in Javascript (jQuery is acceptable as well).

我需要帮助设计一个函数,该函数将返回 Javascript 中两个字符串数组之间的差异(jQuery 也是可以接受的)。

I am basically looking for a function that calculates array A minusB.

我基本上是在寻找一个计算数组 A减去B的函数。

So if we have the followin"

所以如果我们有以下“

A = ['Istanbul', 'Hong Kong', 'Berlin'];
B = ['Berlin', 'Bonn'];

Calling diff = minus(A,B)should result with diffbeing populated with the following values ['Istanbul', 'Hong Kong']

调用的diff = minus(A,B)结果应该diff是填充了以下值['Istanbul', 'Hong Kong']

I do not want to use an additional library like JS Set.

我不想使用像JS Set.

Please help with suggestions ...

请帮忙提出建议...

回答by Casey Chu

function diff(A, B) {
    return A.filter(function (a) {
        return B.indexOf(a) == -1;
    });
}

回答by adeneo

The fastest would probably be a regular loop

最快的可能是常规循环

var A = ['Istanbul', 'Hong Kong', 'Berlin'],
    B = ['Berlin', 'Bonn'],
    C = [];

for (var i=A.length; i--;) {
   if (B.indexOf(A[i]) === -1) 
       C.push(A[i]);
}

console.log(C);

The most elegant is opinion-based, but something like

最优雅的是基于意见的,但像

var A = ['Istanbul', 'Hong Kong', 'Berlin'],
    B = ['Berlin', 'Bonn'];

var C = A.filter(x => !B.includes(x));

console.log(C);

回答by ?ime Vidas

Here:

这里:

var minus = function ( a, b ) {
    return a.filter(function ( name ) {
        return b.indexOf( name ) === -1;
    });
};

Live demo:http://jsfiddle.net/SjF9p/

现场演示:http : //jsfiddle.net/SjF9p/