何が最高速のものでもこれまでにない計算がセットに差をJavascriptの配列のイ?

StackOverflow https://stackoverflow.com/questions/1723168

質問

ましょう AB すると両セットが登場です。を探してい 本当に イノベーションを再構築するには優雅な方法で計算するための、セット差A - B または A \B, お好みに応じて)とします。二つのセットアップ操作としてJavascriptの配列としてのタイトルと言います。

注記:

  • Gecko-特技は大丈夫
  • 私好みのこだわりネイティブ機能のもの(住所】高知県高知市大川筋軽量図書館の場合の方がはるかに速)
  • 私は見られないが、確認しておりません, JS.セット (以前のポイント)

編集: んのコメントが約定を含む複製します。"と言うと"セット"というのは数学的定義する手段など)を含有していない複製します。

役に立ちましたか?

解決

これが最も効果的である場合はわからない場合は、おそらく最短

A = [1, 2, 3, 4];
B = [1, 3, 4, 7];

diff = A.filter(function(x) { return B.indexOf(x) < 0 })

console.log(diff);

ES6に更新ます:

A = [1, 2, 3, 4];
B = [1, 3, 4, 7];

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

console.log(diff);

他のヒント

さて、7年後、 ES6のセットとオブジェクトには、(まだありませんニシキヘビAとしてコンパクトなど - B)は非常に簡単です大きな配列のために、と伝え速くindexOfよります:

console.clear();
let a = new Set([1, 2, 3, 4]);
let b = new Set([5, 4, 3, 2]);


let a_minus_b = new Set([...a].filter(x => !b.has(x)));
let b_minus_a = new Set([...b].filter(x => !a.has(x)));
let a_intersect_b = new Set([...a].filter(x => b.has(x))); 

console.log([...a_minus_b]) // {1}
console.log([...b_minus_a]) // {5}
console.log([...a_intersect_b]) // {2,3,4}

あなたは<のhref = "https://stackoverflow.com/questions/1723168/what-is-the-fastest-or-のようBの各要素に対して直線的にスキャンするAを避けるために、マップとしてオブジェクトを使用することができます最もエレガントウェイ・ツー・計算・設定差-使用-javascr / 1723220#1723220" > user187291の回答するます:

function setMinus(A, B) {
    var map = {}, C = [];

    for(var i = B.length; i--; )
        map[B[i].toSource()] = null; // any other value would do

    for(var i = A.length; i--; ) {
        if(!map.hasOwnProperty(A[i].toSource()))
            C.push(A[i]);
    }

    return C;
}

href="https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Object/toSource" rel="nofollow noreferrer"> toSource()方法のをするために使用される非標準のtoSource()呼び出しをドロップすることで、コードをスピードアップすることができます。

最短は、jQueryのを使用して、ある

var A = [1, 2, 3, 4];
var B = [1, 3, 4, 7];

var diff = $(A).not(B);

console.log(diff.toArray());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Iは、配列A Bに存在しないから値を保持、次いで、アレイBをハッシュなります

function getHash(array){
  // Hash an array into a set of properties
  //
  // params:
  //   array - (array) (!nil) the array to hash
  //
  // return: (object)
  //   hash object with one property set to true for each value in the array

  var hash = {};
  for (var i=0; i<array.length; i++){
    hash[ array[i] ] = true;
  }
  return hash;
}

function getDifference(a, b){
  // compute the difference a\b
  //
  // params:
  //   a - (array) (!nil) first array as a set of values (no duplicates)
  //   b - (array) (!nil) second array as a set of values (no duplicates)
  //
  // return: (array)
  //   the set of values (no duplicates) in array a and not in b, 
  //   listed in the same order as in array a.

  var hash = getHash(b);
  var diff = [];
  for (var i=0; i<a.length; i++){
    var value = a[i];
    if ( !hash[value]){
      diff.push(value);
    }
  }
  return diff;
}

を盛り込んだデクリストにしてカップルでの繰り返し処理の方法には配列やオブジェクト/ハッシュ(each 友人までセット差連合(eu)との交差点に比例した時間約20ライン合計

var setOPs = {
  minusAB : function (a, b) {
    var h = {};
    b.each(function (v) { h[v] = true; });
    return a.filter(function (v) { return !h.hasOwnProperty(v); });
  },
  unionAB : function (a, b) {
    var h = {}, f = function (v) { h[v] = true; };
    a.each(f);
    b.each(f);
    return myUtils.keys(h);
  },
  intersectAB : function (a, b) {
    var h = {};
    a.each(function (v) { h[v] = 1; });
    b.each(function (v) { h[v] = (h[v] || 0) + 1; });
    var fnSel = function (v, count) { return count > 1; };
    var fnVal = function (v, c) { return v; };
    return myUtils.select(h, fnSel, fnVal);
  }
};

eachfilter 定義された配列としてユーティリティメソッド:

  • myUtils.keys(hash):を返します。 配列のキーのハッシュ

  • myUtils.select(hash, fnSelector, fnEvaluator):配列を返しますと その結果を呼び出す fnEvaluator のキーと値のペアになる fnSelector はtrueを返します。

select() はゆるやかに刺激によるCommon Lispではな filter()map() すべて一つに収められています。(きるようにして定義されて Object.prototype, その難破船は爆jQueryので、落ち着いた静ユーティリティメソッド.)

性能:試験

var a = [], b = [];
for (var i = 100000; i--; ) {
  if (i % 2 !== 0) a.push(i);
  if (i % 3 !== 0) b.push(i);
}

二つセット50,000 66,666ます。これらの値のA-B間75msが連合(eu)との交差点をはい150msいます。(Mac Safari4.0,Javascriptを使用日のためのタイミングでした。)

それでいいんじゃないも利得のための20を行います。

使用 Underscore.js の(機能JSのためのライブラリ)

>>> var foo = [1,2,3]
>>> var bar = [1,2,4]
>>> _.difference(foo, bar);
[4]

いくつかの単純な関数、ミラノの答え@からの借入ます:

const setDifference = (a, b) => new Set([...a].filter(x => !b.has(x)));
const setIntersection = (a, b) => new Set([...a].filter(x => b.has(x)));
const setUnion = (a, b) => new Set([...a, ...b]);

使用方法:

const a = new Set([1, 2]);
const b = new Set([2, 3]);

setDifference(a, b); // Set { 1 }
setIntersection(a, b); // Set { 2 }
setUnion(a, b); // Set { 1, 2, 3 }

として、断食中の方のこないのではない優雅なもの思いはいくつかの試験でした。荷重一配列オブジェクトとしてははるかに速く処理大量:

var t, a, b, c, objA;

    // Fill some arrays to compare
a = Array(30000).fill(0).map(function(v,i) {
    return i.toFixed();
});
b = Array(20000).fill(0).map(function(v,i) {
    return (i*2).toFixed();
});

    // Simple indexOf inside filter
t = Date.now();
c = b.filter(function(v) { return a.indexOf(v) < 0; });
console.log('completed indexOf in %j ms with result %j length', Date.now() - t, c.length);

    // Load `a` as Object `A` first to avoid indexOf in filter
t = Date.now();
objA = {};
a.forEach(function(v) { objA[v] = true; });
c = b.filter(function(v) { return !objA[v]; });
console.log('completed Object in %j ms with result %j length', Date.now() - t, c.length);

結果:

completed indexOf in 1219 ms with result 5000 length
completed Object in 8 ms with result 5000 length

しかし、この動作 文字列のみ.計画がある場合は比較番号を設定してください図結果 parseFloat.

これは動作しますが、私は別のものがあまりにもはるかに短く、かつエレガントだと思います。

A = [1, 'a', 'b', 12];
B = ['a', 3, 4, 'b'];

diff_set = {
    ar : {},
    diff : Array(),
    remove_set : function(a) { ar = a; return this; },
    remove: function (el) {
        if(ar.indexOf(el)<0) this.diff.push(el);
    }
}

A.forEach(diff_set.remove_set(B).remove,diff_set);
C = diff_set.diff;
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top