JavaScript:迭代多维数组并提取多个搜索值

时间:2014-06-13 23:40:27

标签: javascript arrays multidimensional-array

我想做什么:

使用多个搜索字符串搜索多维数组。

我目前正在做的例子:

var multiArray = [['Apples and pears', 'tuna salad'],['bananas tuna'],['the colour blue']];

var singleArray = [];

var match_array = [];

// Turn multiple arrays into one big one
    for (var i = 0; i < multiArray.length; i++) {

        for (var x = 0; x < multiArray[i].length; x++) {

            singleArray.push(multiArray[i][x]);
    }
}

// Create a new array from matched strings

function find_match(to_match) {

    for (var i in singleArray) {

        if (singleArray[i].indexOf(to_match)!= -1)

        match_array.push(singleArray[i]);
    }

    return (match_array.length === 0 ? null : match_array);

}

// Find matching terms for match_array
find_match('tuna');
find_match('the');

alert(match_array);

JSFiddle Demo

问题:

  1. 显然,这是一种混乱的方式。怎么会这样 精简(即直接搜索multiArray而不是使用 多个find_match函数)?

  2. 如何才能获得精确的字符串匹配,最好不要破坏多维数组?

  3. 您对搜索大量内容有什么看法? 多维数组?

1 个答案:

答案 0 :(得分:0)

你想要这样的东西吗?

var multiArray = [['Foo', 'Bar'],['Foo'],['Bar']];

var singleArray = [];

var match_array = [];

// Turn multiple arrays into one big one
for (var i = 0; i < multiArray.length; i++) {
    for (var x = 0; x < multiArray[i].length; x++) {
        singleArray.push(multiArray[i][x]);
    }
}

// Create a new array from matched strings
function find_match(to_match, where_search) {

    for (var j in where_search) {
        if(where_search[j] instanceof Array){
           find_match(to_match, where_search[j]);

        }else{
            for (var i in to_match) {
                if (where_search[j].indexOf(to_match[i]) ==0 && 
                    where_search[j].length == to_match[i].length)
                    match_array.push(where_search[j]);
            }
        }
    }

    return (where_search.length === 0 ? null : match_array);

}

// Find matching terms for match_array
find_match(['Foo', 'Bar'],multiArray);

alert(match_array);