簡體   English   中英

如何根據不同數組中相同元素的索引獲取數組中每個元素的索引?

[英]How to get the index of each element of an array based on the indexes of the same elements in a different array?

我的引用數組是“functionsvalues”,它表示元素:“All”、“Fe”、“Fi”、“Te”、“Ti”、“Se”、“Si”、“Ne”、“Ni”正確的順序。

現在我需要得到一個數字列表,這些數字將表達這些相同元素重新排列的順序,在這種情況下是:'Fe'、'Si'、'Ne'、'Ti'、'Fi'、'Se'、'Ni ', '特'

引用數組:functionsvalues = ['All', 'Fe', 'Fi', 'Te', 'Ti', 'Se', 'Si', 'Ne', 'Ni']

我想要自定義順序的數組:chosenfunctionsvalues = ['Fe', 'Si', 'Ne', 'Ti', 'Fi', 'Se', 'Ni', 'Te']

期望 output:[1, 6, 7, 4, 2, 5, 8, 3]

您可以采用 object 和 map 索引。

 const values = ['All', 'Fe', 'Fi', 'Te', 'Ti', 'Se', 'Si', 'Ne', 'Ni'], indices = Object.fromEntries(values.map((k, i) => [k, i])), given = ['Fe', 'Si', 'Ne', 'Ti', 'Fi', 'Se', 'Ni', 'Te'], result = given.map(k => indices[k]); console.log(...result);

這是你能做的。

 var arr = ['All', 'Fe', 'Fi', 'Te', 'Ti', 'Se', 'Si', 'Ne', 'Ni']; var anotherArray = ['Fe', 'Si', 'Ne', 'Ti', 'Fi', 'Se', 'Ni', 'Te']; var mapofIndices = {}; arr.forEach((a, i)=>{ mapofIndices[a] = i; }) var result = anotherArray.map(x=>mapofIndices[x]) console.log(result)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM