Example:
["a", "b"] -> 1
["c", "d", "e"] -> 2
I want to be able to give "d" as key and get 2.
Example:
["a", "b"] -> 1
["c", "d", "e"] -> 2
I want to be able to give "d" as key and get 2.
This work with your example, but I am not sure it covers your real life case :D
const arrays = [['a','b'],['c','d','e']]
const struct = arrays.reduce((acc, array, index) => {
array.forEach(v => acc[v] = index + 1)
return acc
}, {})
console.log(struct)
console.log(struct.d)
output
{a: 1, b: 1, c: 2, d: 2, e: 2}
2
You could just use an object like this:
{
"a": 1,
"b": 1,
"c": 2,
"d": 2,
"e": 2,
}
but this has the problem of if you wanted to change all 1s to 3, you'd have to change it in each place.
You can do this:
const data = [1, 2];
const map = {
"a": data[0],
"b": data[0],
"c": data[1],
"d": data[1],
"e": data[1],
}
so that you only have to set the result in one place.
you can also do stuff with Sets or nested arrays, but that prevents the lookup from being O(1) and changes it to O(n) or O(n*m) based on implementation.
Not sure if exactly what you are looking for but you can do it with built-in object and array methods.
Object.fromEntries(
Object.entries(["c", "d", "e"]).map((a) => {
a.reverse();
a[1] = Number(a[1]);
return a;
})
);
This will output:
{ c: 0, d: 1, e: 2 }
But I see you want to start from 1 and not 0, in that case you could map bit more:
Object.fromEntries(
Object.entries(["c", "d", "e"]).map((a) => {
a.reverse();
a[1] = Number(a[1]) + 1;
return a;
})
);
Then you get
{ c: 1, d: 2, e: 3 }