比较和过滤两个数组

时间:2015-05-22 06:16:55

标签: javascript arrays loops filter array-splice

我一直在尝试用两个数组实现一个函数,

array1 的元素用作过滤掉 array2 中元素的条件。

例如:

array1= [apple, grapes, oranges]

array2= [potato, pears, grapes, berries, apples, oranges]

在输入函数后,array2应该包含这样的元素:

filter_twoArrays(array1,array2)

array2= [grapes, apples, oranges]

我尝试了以下代码,使用for循环和array.splice(),但我看到的问题是当我使用splice方法时,它似乎改变了for循环中array2的长度:

function filter_twoArrays(filter,result){

  for(i=0; i< filter.length; i++){
    for(j=0; j< result.length; j++){
      if(filter[i] !== result[j]){
        result.splice(j,1)
      }
    }
  }

如何优化过滤功能

将非常感谢任何输入

喝彩!

5 个答案:

答案 0 :(得分:12)

您可以使用filter,如下所示

&#13;
&#13;
var array1 = ['apples', 'grapes', 'oranges', 'banana'],
  array2 = ['potato', 'pears', 'grapes', 'berries', 'apples', 'oranges'];

var intersection = array1.filter(function(e) {
  return array2.indexOf(e) > -1;
});

console.log(intersection);
&#13;
&#13;
&#13;

您也可以在Array原型上添加此方法,并直接在数组

上调用它

&#13;
&#13;
Array.prototype.intersection = function(arr) {
  return this.filter(function(e) {
    return arr.indexOf(e) > -1;
  });
};

var array1 = ['apples', 'grapes', 'oranges', 'banana'],
  array2 = ['potato', 'pears', 'grapes', 'berries', 'apples', 'oranges'];

var intersection = array1.intersection(array2);
console.log(intersection);
&#13;
&#13;
&#13;

答案 1 :(得分:0)

嗨,这是一个函数array_intersect php的移植。应该对你有好处 http://phpjs.org/functions/array_intersect/

function array_intersect(arr1) {
  //  discuss at: http://phpjs.org/functions/array_intersect/
  // original by: Brett Zamir (http://brett-zamir.me)
  //        note: These only output associative arrays (would need to be
  //        note: all numeric and counting from zero to be numeric)
  //   example 1: $array1 = {'a' : 'green', 0:'red', 1: 'blue'};
  //   example 1: $array2 = {'b' : 'green', 0:'yellow', 1:'red'};
  //   example 1: $array3 = ['green', 'red'];
  //   example 1: $result = array_intersect($array1, $array2, $array3);
  //   returns 1: {0: 'red', a: 'green'}

  var retArr = {},
    argl = arguments.length,
    arglm1 = argl - 1,
    k1 = '',
    arr = {},
    i = 0,
    k = '';

  arr1keys: for (k1 in arr1) {
    arrs: for (i = 1; i < argl; i++) {
      arr = arguments[i];
      for (k in arr) {
        if (arr[k] === arr1[k1]) {
          if (i === arglm1) {
            retArr[k1] = arr1[k1];
          }
          // If the innermost loop always leads at least once to an equal value, continue the loop until done
          continue arrs;
        }
      }
      // If it reaches here, it wasn't found in at least one array, so try next value
      continue arr1keys;
    }
  }

  return retArr;
}

答案 2 :(得分:0)

由于您已经标记了javascript,因此这是解决方案。

function f1(x, y) {
    var t = y.slice(0);
    var r = [];
    for (var i = 0; i < x.length; i++) {
        for (var j = 0; j < y.length; j++) {
            if (x[i] === y[j]) {
                [].push.apply(r, t.splice(j, 1));
            }
        }
    }
    console.log(r)
    y.length = 0;
    [].push.apply(y, r);
}

答案 3 :(得分:0)

以下是一种基于代码的简单方法

function array_filter(filter, result) {
    var filterLen = filter.length;
    var resultLen = result.length;

    for (i = 0; i < resultLen; i++) {
        for (j = 0; j < filterLen; j++) {
            if (!contains(filter, result[i]))
                result.splice(i, 1);
        }
    }
}

//Return boolean depending if array 'a' contains item 'obj'
function contains(array, value) {
    for (var i = 0; i < array.length; i++) {
        if (array[i] == value) {
            return true;
        }
    }
    return false;
}

答案 4 :(得分:0)

通过delete result[index]标记要过滤掉的项目,根据需要进行操作。

的JavaScript

window.onload = runs;

function runs() {
    var array1 = ["apples", "grapes", "oranges"];
    var array2 = ["potato", "pears", "grapes", "berries", "apples", "oranges"];
    var result = filter_twoArrays(array1, array2);

    function filter_twoArrays(filter, result) {
        var i = 0,
            j = 0;
        for (i = 0; i < result.length; i++) {
            var FLAG = 0;
            for (j = 0; j < filter.length; j++) {
                if (filter[j] == result[i]) {
                    FLAG = 1;
                }
            }
            if (FLAG == 0) delete result[i];
        }
        return result;
    }

    var body = document.getElementsByTagName("body")[0];
    var i = 0;
    for (i = 0; i < result.length; i++) {
        if (result[i] !== undefined)
            body.innerHTML = body.innerHTML + result[i] + " ";
    }
}