比较和筛选两个数组 [英] Comparing and Filtering two arrays
问题描述
我一直想在那里有两个数组给实现一个函数,
I've been trying to implement a function where given with two arrays,
数组1 的元素作为条件,筛选出在元素的数组2
array1's elements is used as conditions to filter out elements in array2.
例如:
array1= [apple, grapes, oranges]
array2= [potato, pears, grapes, berries, apples, oranges]
送入一个函数之后,数组2应具有元素作为这样:
After feeding into a function, array2 should have elements as such:
filter_twoArrays(array1,array2)
array2= [grapes, apples, oranges]
我试过以下code,使用循环和方法Array.splice(),但我看到的问题是,当我用拼接的方法,似乎它改变的数组2的长度循环:
I've tried the following code, using for loops and array.splice(), but the problem I am seeing is that when I use the splice method, it seems that it changes the lengths of array2 in the for loop:
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)
}
}
}
任何输入将pciated如何完善过滤功能大大AP $ P $
Any inputs will be greatly appreciated on how to refine the filter function
干杯!
推荐答案
标志,它是通过被过滤掉的项目删除结果[指数]
根据需要操纵它们。
Mark the items which are to be filtered out via delete result[index]
manipulate them as needed.
的的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] + " ";
}
}
这篇关于比较和筛选两个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!