Suppose, we have an array of string literals like this −
const arr = [ "fiat−palio", "fiat−stilo", "fiat−strada", "fiat−uno", "fiat−uno", "gm−corsa", "gm−celta", "ford−fiesta", "volkswagen−gol", "volkswagen−gol", "volkswagen−gol", "volkswagen−voyage" ]
We are required to write a JavaScript function that takes in one such array of strings. In the above array, all the entries have one thing in common (besides all being a string), they all have a string pair separated by a dash ('−').
Our function should prepare an object that contains keys as the part before the dash ('−) and their values as objects which contains the count of each string they were within the original array.
Therefore, for the above array, the output should look like this −
const output = {
"fiat": {
"palio": 1,
"stilo": 1,
"strada": 1,
"uno": 2
},
"gm": {
"corsa": 1,
"celta": 1
},
"ford": {
"fiesta": 1
},
"volkswagen": {
"gol": 3,
"voyage": 1
}
};Example
The code for this will be −
const arr = [
"fiat−palio",
"fiat−stilo",
"fiat−strada",
"fiat−uno",
"fiat−uno",
"gm−corsa",
"gm−celta",
"ford−fiesta",
"volkswagen−gol",
"volkswagen−gol",
"volkswagen−gol",
"volkswagen−voyage"
];
const convertToObject = (arr = []) => {
let res = arr.reduce((acc, val) => {
let pair = val.split('−');
let mark = pair[0];
let model = pair[1];
if(!acc.hasOwnProperty(mark)) {
acc[mark] = {};
acc[mark][model] = 1;
} else {
if(acc[mark].hasOwnProperty(model)) {
acc[mark][model] += 1;
} else {
acc[mark][model] = 1;
}
}
return acc;
}, {})
return res;
}
console.log(convertToObject(arr));Output
And the output in the console will be −
{
fiat: { palio: 1, stilo: 1, strada: 1, uno: 2 },
gm: { corsa: 1, celta: 1 },
ford: { fiesta: 1 },
volkswagen: { gol: 3, voyage: 1 }
}