2017-02-20 54 views
0

我目前有這個問題,我似乎無法找到特定於我的問題的答案。使用另一個陣列從陣列中查找信息

Array1 = ["item1", "item2", "item3", "item4", "item5"] 
Array2 = ["item2", "item5"] 

我正在尋找使用array1中的信息在array1中查找。

一個例子這種輸出

數組1具有ITEM2,並在數組1 [1]

如果有人能幫助我,謝謝。

+0

爲什麼沒有你的例子輸出提'「ITEM5」'? 'Array1'中的同一個字符串可能會不止一次出現?你試過什麼了?我正在考慮一個簡單的'for'循環來調用'Array1.indexOf()'就可以輕鬆完成任務。如果你的問題是「請爲我編碼整個事情」你真正想要的是一個JS教程 - 有[SO JS信息頁面]上的一些鏈接(http://stackoverflow.com/tags/javascript/info) 。 – nnnnnn

+0

你的問題是什麼?你只是陳述了關於數組 –

回答

2
Array2.forEach((e) => { 
    const indexOfE = Array1.indexOf(e) 
    if (indexOfE > -1) { 
     console.log(`Array1 has ${e} and is at Array1[${indexOfE}]`) 
    } 
}) 

你可以看看forEachindexOftemplate literals幫助你明白這個代碼。

編輯

回答這個問題的意見,如果你想檢查數組1包含數組2的元素作爲子元素,那麼您可以:

Array2.forEach((e) => { 
    Array1.forEach((f, i) => { 
     if (f.toLowerCase().includes(e)) { 
      console.log(`Array1 has ${e} and is at Array1[${i}]`) 
     } 
    }) 
}) 

檢查String.prototype.includesthis answer有關在另一個字符串中查找子字符串的詳細信息。

+0

傑出的答案。謝謝。一個問題。有沒有可能''Array2'搜索更多的術語來查找這個詞,無論它是如何在'Array1'中?更像是包含或包含方法。例如說它是「largeitem1」,而「Array2」仍然有「item1」 – UndefinedUsername

+0

@UndefinedUsername是,請檢查編輯是否有答案。 –

0

如果你只是想知道數組1包含數組2的元素,然後遍歷數組2呼籲的indexOf每個元素:

Array2.map((el => { 
    if (Array1.indexOf(el) !== -1) { 
     console.log('Array 1 contains ' + el); 
    } 
})); 
+1

的事實,'.forEach()'是比'.map()'更好的選擇。結果是一樣的,但'.map()'意味着你是*映射*的東西。你不是。 – nnnnnn

+0

是的,你是對的。我傾向於選擇出於習慣的地圖 - 但這裏的foreach更好。 –

0

這是代碼:

var Array1 = ["item1", "item2", "item3", "item4", "item5"]; 
var Array2 = ["item2", "item5"]; 
for (var i = 0; i <Array2.length; i++) { 
if (Array1.indexOf(Array2[i])>-1) { 
console.log("Array1 has "+Array2[i]+" and is at Array1["+Array1.indexOf(Array2[i]) +"]") 
    } 
} 
0

你可以Ramdajs找到兩個數組的交集如下

const Array1 = ["item1", "item2", "item3", "item4", "item5"]; 
const Array2 = ["item2", "item5"]; 

const res = R.intersection(Array1, Array2); 
console.log(res); 

here是代碼擊退

同樣可以使用lodash實現

const Array1 = ["item1", "item2", "item3", "item4", "item5"]; 
const Array2 = ["item2", "item5"]; 
const res = _.intersection(Array1, Array2) 
console.log(res); 

here是lodash的jsfiddle。

,或者您可以使用包括陣列的方法做同樣的

const Array1 = ["item1", "item2", "item3", "item4", "item5"]; 
 
const Array2 = ["item2", "item5"]; 
 
const res = Array1.filter(curr=>Array2.includes(curr)); 
 
console.log(res);

+1

,你被ramda迷住了。 –