I think your approach is just fine.
You are concerned about getting 5 lists because biggest number is 5, so you can use a map with the value. The map's keys are the unique values of the array.
Here is a concrete code suggestion in JavaScript. You can try it easily in any browser debug console, just copy it into the console:
// 1. Create a test array
var mainList = [5,0,3,5,2,5,3];
// 2. To get a map, we need some unique() function for an array:
function unique(rawArray) {
var arr = [];
for(var i = 0; i < rawArray.length; i++) {
if(arr.indexOf(rawArray[i]) < 0) {
arr.push(rawArray[i]);
}
}
return arr;
}
// At this point, you get for mainList:
// [5, 0, 3, 5, 2, 5, 3]
// And for unique(mainList);:
// [5, 0, 3, 2]
// 3. Now we create a function to get the index lists:
function createMaps(uniqueList, mainList) {
// Create and init maps.
var maps = {};
for (var u=0; u<uniqueList.length; u++) {
// Create a map entry and init it with an array.
maps[uniqueList[u]] = [];
// Fill the array with indices.
for (var i=0; i<mainList.length; i++) {
if (mainList[i] == uniqueList[u]) {
maps[uniqueList[u]].push(i);
}
}
}
return maps;
}
// 4. Now let's put the thing together:
var uniqueList = unique(mainList);
var maps = createMaps(uniqueList, mainList);
// (end of script)
Maps will look like this:
Object {0: Array[1], 2: Array[1], 3: Array[2], 5: Array[3]}
0: Array[1]
0: 1
2: Array[1]
0: 4
3: Array[2]
0: 2
1: 6
5: Array[3]
0: 0
1: 3
2: 5
Which is exactly what you wished. You see, your idea is fine.
Finally, you mentioned a "more efficient" way. This is not very specific. To get concrete answers, try to test your idea against scenarios:
- What happens to all your index lists if you remove a value from your main list? --> Many lists must be updated.
- dito : What happens to all your index lists if you add / insert / swap ... values into the main list?
- How is the performance of building a set of lists?
- What happens if you wish to combine values for indices (e.g. like you have combined indices in a relational SQL table)? How much resistance do you feel from your model?
and so on. Like this, you will see different aspects of "efficient".