2

I have the following data. I would like to be able to efficiently filter out all of the objects in the sites array that do not have a matching segmentCode in array of segmentCodes. I can use dojo or native javascript, but I do not have access to any other libraries.

var segmentCodes = ["10", "20","30","40"];
var sites = [
    {"siteid":1, "segmentCode":"10"},
    {"siteid":2, "segmentCode":"10"},
    {"siteid":3, "segmentCode":"20"},
    {"siteid":4, "segmentCode":"30"},
    {"siteid":5, "segmentCode":"70"},
    {"siteid":6, "segmentCode":"999"}];

The result should look like this:

[{"siteid":5, "segmentCode":"70"}, {"siteid":6, "segmentCode":"999"}]

Thanks in advance.

4

4 に答える 4

2

Array.filterArray.indexOfを使用してみてください

var res = sites.filter(function( o){
  return segmentCodes.indexOf(o.segmentCode) == -1;
});

デモ

于 2013-10-15T15:05:10.837 に答える
1

効率的な解決策はsegmentCodes、マップに変換することです。

map = segmentCodes.reduce(function(o, x) { return o[x] = 1, o }, {})

次に、O(1) ルックアップを使用してコードをフィルタリングします。

result = sites.filter(function(x) { return !(x.segmentCode in map) })

これをさらに高速化したい場合は、イテレータ関数を単純なループに置き換えます。

于 2013-10-15T15:06:29.837 に答える
0

CLJ!これをチェックしてください!

var segmentCodes = ["10", "20","30","40"];
var sites = [
    {"siteid":1, "segmentCode":"10"},
    {"siteid":2, "segmentCode":"10"},
    {"siteid":3, "segmentCode":"20"},
    {"siteid":4, "segmentCode":"30"},
    {"siteid":5, "segmentCode":"70"},
    {"siteid":6, "segmentCode":"999"}];
var segmentCodes = ["10", "20","30","40"];

Array.prototype.filter = function(fun, notMatchArray) {
    'use strict';

    if (!this) {
      throw new TypeError();
    }

    var objects = Object(this);
    var len = objects.length >>> 0;
    if (typeof fun !== 'function') {
      throw new TypeError();
    }

    var res = [];
    var thisp = arguments[1];
    for (var i in objects) {
      if (objects.hasOwnProperty(i)) {
        if(notMatchArray.indexOf(objects[i].segmentCode) === -1)
            res.push(objects[i]);
      }
    }
    fun.call(thisp, res);
};

sites.filter(function(result){
    console.log('result', result);
}, segmentCodes); 

参照: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

于 2013-10-15T15:32:57.560 に答える