0

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.

avaris
  • 41
  • 3
  • getAllIndexes is returning an array; if you only want it to return a single value which you can use as an index on listID, you need to make getAllIndexes return an integer. – Caleb George Jun 04 '21 at 17:40
  • @CalebGeorge He wants all the indexes. See `"5,9"` in the desired result. – Barmar Jun 04 '21 at 17:41

2 Answers2

0

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.

Barmar
  • 741,623
  • 53
  • 500
  • 612
0

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);
mhodges
  • 10,938
  • 2
  • 28
  • 46