Basically, I need to regroup keys by values from an object to an array
An example worth a thousand words in my case, as I don't know how to clearly explain my problem.
Here is my input object:
{
"Data 1": 0,
"Data 2": 1,
"Data 3": 3,
"Data 4": 0
}
What I should output:
[
["Data 1", "Data 4"], // data 1 and 4 are grouped as they both "worth" 0
["Data 2"], // data 2 is alone to "worth" 1
["Data 3"] // data 3 is alone to "worth" 3
]
First solution:
var output = [];
for (var data in input) { // my input object
var value = input[data];
if (output[value] == undefined) {
output[value] = [];
}
output[value].push(data);
}
console.log(output);
It works well for most of the cases, except the one presented at the beginning: if I skip a value - say 0, 1, 3 - then my output will be
[
0: ["Data 1", "Data 4"],
1: ["Data 3"],
3: ["Data 4"]
]
What I understood so far is that since the key 2
is missing, JavaScript somehow understand the output as an associative array.
Final solution:
From the code below, I used a "trick", making an equivalent of array_values()
from PHP:
function array_values(arr) {
var tmp = [];
for (key in arr) {
tmp[tmp.length] = arr[key];
}
return tmp;
}
var output = [];
for (var data in input) { // my input object
var value = input[data];
if (output[value] == undefined) {
output[value] = [];
}
output[value].push(data);
}
console.log(array_values(output));
This finally works perfectly fine.
Nevertheless, I feel like I could optimize and simplify my code. I fear that a big object could be long to process since I could have to parse it 2 times. Does anyone have a guess?