Сравните строковые элементы массива со свойством элементов объекта другого массива - PullRequest
0 голосов
/ 17 марта 2012

Итак, заголовок говорит о большей части, и я приведу пример:

var foo = ['one', 'two', 'three'];
var bar = [
        {   
            integer: 1,
            string: 'one'
        },
        {   
            integer: 3,
            string: 'three'
        }       
    ];

Теперь мне интересно, как я могу получить список положительных совпадений для каждого из элементов в foo для каждого из string свойств всех объектов в массиве bar.

Ответы [ 4 ]

4 голосов
/ 17 марта 2012

Сначала создайте набор всех элементов в foo, чтобы избежать сложности квадрата:

var fooSet = {};    
for(var i = 0; i < foo.length; i++) {
    var e = foo[i];
    fooSet[e] = true;
}

Затем пройдите bar и соберите совпадения:

var matches = [];
for(var i = 0; i < bar.length; i++) {
    var e = bar[i];
    if(fooSet[e.string]) {
           matches.push(e);
    }
}

Послеэтот массив matches будет содержать элементы из bar, которые соответствуют элементам foo.

Вот живой пример:

0 голосов
/ 17 марта 2012

Эти 2 работы. Зависит от того, как вы хотите использовать данные, которые вы можете изменить.

http://jsfiddle.net/KxgQW/5/

ПУТЬ ОДИН

//wasn't sure which one you want to utilize so I'm doing both
//storing the index of foo to refer to the array
var wayOneArrayFOO= Array();
//storing the index of bar to refer to the array
var wayOneArrayBAR= Array();

var fooLength = foo.length;
var barLength = bar.length;


/*THE MAGIC*/                
//loop through foo
for(i=0;i<fooLength;i++){

    //while your looping through foo loop through bar        
    for(j=0;j<barLength;j++){
        if(foo[i]==bar[j].string){
            wayOneArrayFOO.push(i);
            wayOneArrayBAR.push(j);    
        }
    }

}

ПУТЬ ДВА

//storing the value of foo
var wayTwoArrayFOO= Array();
//storing the value of bar
var wayTwoArrayBAR= Array();            


/*THE MAGIC*/      
//loop through foo
for(i=0;i<fooLength;i++){

    //while your looping through foo loop through bar        
    for(j=0;j<barLength;j++){
        if(foo[i]==bar[j].string){
            wayTwoArrayFOO.push(foo[i]);
            wayTwoArrayBAR.push(bar[j]);    
        }
    }

}
0 голосов
/ 17 марта 2012

Это:

// foo & bar defined here

// put all the keys from the foo array to match on in a dictionary (object)
var matchSet = {};
for (var item in foo)
{
    var val = foo[item];
    matchSet[val] = 1;
}

// loop through the items in the bar array and see if the string prop is in the matchSet
// if so, add it to the matches array
var matches = [];
for (var i=0; i < bar.length; i++)
{
    var item = bar[i];
    if (matchSet.hasOwnProperty(item['string']))
    {
        matches.push(item['string']);
    }
}

// output the matches (using node to output to console)
for (var i in matches)
{
    console.log(matches[i]);
}

Выходы:

match: one
match: three

ПРИМЕЧАНИЕ: использование узла для интерактивного запуска

0 голосов
/ 17 марта 2012

Перебрать один из массивов, сравнивая каждый элемент с другим:

var matches = [],
    i, j;

for (i=0; i < bar.length; i++)
    if (-1 != (j = foo.indexOf(bar[i].string)))
       matches.push(foo[j]);

// matches is ['one', 'three']

Очевидно, что если вы хотите, чтобы matches содержал элементы из bar вместо foo, просто измените выражение .push() на matches.push(bar[i]);.

Конечно, вышеизложенное предполагает, что вы не заботитесь о поддержке старых браузеров, которые не поддерживают .indexOf() для массивов, или что вы можете использовать shim .

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...