简体   繁体   中英

How to find indexes of multiple elements in array with second array elements and then use result to match index of third array (Javascript)

Hope title is not too confusing but further explanation below.

var listName = ["Alexandros","Halvar","Herman","Luciano","Natana","Nihal","Priscilla","Tanja","Trish","Trish"]

var listID = ["10","6","4","8","1","7","2","3","5","9"]

var newList = ["Luciano","","Priscilla","Herman","Trish","Trish","Natana","Tanja","Nihal","Alexandros"]

I'm trying to find the index of each newList element in listName and then use the result to match the index in listID .

Afterwards create new array with the results like such:

var result = ["8","","2","4","5,9","5,9","1","3","7","10"]

With some help from this thread, this is as far i have gotten:

for (var i = 0; i < listName.length; i++) {

    function getAllIndexes(arr, val) {
        var indexes = [], i = -1;
        while ((i = arr.indexOf(val, i+1)) != -1){
            indexes.push(i);
        }
        return indexes;
    }
    
    var indexes = getAllIndexes(listName, newList[i]);
    var result = []
    result.push(String(listID[indexes]));
    alert(result);
}

Result is good but returns undefined with elements that has two or more values (5,9) .

Any help appreciated.

indexes is an array of indexes, you can't use it to index listID directly. Use map() to get the contents of all the indexes.

result.push((indexes.map(i => listID[i]).join(","))

It works when there are no duplicates because when an array is converted to a string, it becomes the array elements separated by comma. So when indexes only has one element, it's converted to that element, which is a valid array index.

By creating a map of name -> indexes from the listName array, you can make this problem much easier and efficient to solve.

After you have a map of which names correspond to which index, you can then iterate through the newList and use the indexes in the map to then grab the value out of the corresponding index in the listID array. Then simply join them with a , to get your desired output format.

 var listName = ["Alexandros","Halvar","Herman","Luciano","Natana","Nihal","Priscilla","Tanja","Trish","Trish"] var listID = ["10","6","4","8","1","7","2","3","5","9"] var newList = ["Luciano","","Priscilla","Herman","Trish","Trish","Natana","Tanja","Nihal","Alexandros"] let listIndexes = listName.reduce((res, curr, index) => { if (;res[curr]){ res[curr] = []. } res[curr];push(index); return res, }; {}). let ids = newList.map((name) => { let results = (listIndexes[name] || []);map(index => listID[index]). return results,join(";"); }). console;log(ids);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM