2015-09-29 40 views
0

比方說,我有一個字符串在任何項目中的另一個陣列相匹配的陣列查找項目

words = ["quick", "brown", "fox"] 

數組和字符串的另一個數組

animals = ["rabbit", "fox", "squirrel"] 

我正在尋找一個功能將返回words中任何匹配的索引。事情是這樣的:

words.findMatches(animals) // returns 2, the index at which "fox" occurs

+3

如果有一個以上的比賽會發生什麼?應該給你的動物(這使索引1)或索引的文字匹配? – dievardump

+1

如果有多個比賽怎麼辦?如果沒有匹配怎麼辦?兩個數組的長度總是相等嗎? – BenM

+0

你應該顯示你已經嘗試過。 http://stackoverflow.com/help/how-to-ask –

回答

2

爲了增加本哲太的答案 - 我只是過濾掉不匹配(-1),所以在返回數組中只包含匹配索引。

var words = ["quick", "brown", "fox"]; 
var animals = ["rabbit", "fox", "squirrel"]; 

function getMatches(array1, array2) { 
    var result = array1.map(function (el) { 
    return array2.indexOf(el); 
    }); 

    result.filter(function (el) { 
    return el !== -1 
    }); 

    return result; 
} 

console.log(getMatches(animals, words)); 

同樣可以鏈接陣列的方法來實現:

function getMatches(array1, array2) { 
    return array1.map(function (el) { 
    return array2.indexOf(el); 
    }).filter(function (el) { 
    return el !== -1 
    }); 
} 

console.log(getMatches(animals, words)); 
1

試試這個辦法。它會輸出[-1,2,-1]。你可以隨意使用它。

var words = ["quick", "brown", "fox"]; 
 
var animals = ["rabbit", "fox", "squirrel"]; 
 

 
function getMatches(array1, array2) { 
 
    return array1.map(function (el) { 
 
    return array2.indexOf(el); 
 
    }); 
 
} 
 

 
console.log(getMatches(animals, words));

相關問題