My array of reference is "functionsvalues", which presents the elements: 'All', 'Fe', 'Fi', 'Te', 'Ti', 'Se', 'Si', 'Ne', 'Ni' in the correct order.
Now I need to get a list of numbers the will express the order of these same elements rearranged, is this case: 'Fe', 'Si', 'Ne', 'Ti', 'Fi', 'Se', 'Ni', 'Te'
Array of reference: functionsvalues = ['All', 'Fe', 'Fi', 'Te', 'Ti', 'Se', 'Si', 'Ne', 'Ni']
Array for which I want the custom order: chosenfunctionsvalues = ['Fe', 'Si', 'Ne', 'Ti', 'Fi', 'Se', 'Ni', 'Te']
Desired output: [1, 6, 7, 4, 2, 5, 8, 3]
CodePudding user response:
You could take an object and map the indices.
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);
CodePudding user response:
This is what you can do.
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)