I am struggling to transform the input:
["apple", "banana", "carrot", "durian", "eggplant", "apple", "carrot"] into the desired output:
[{ name: "Apple", count: 2 }, { name: "Banana", count: 1 }, { name: "Carrot", count: 2 }, { name: "Durian", count: 1 }, { name: "Eggplant", count: 1 }], where I seem to be having trouble with this incorrect output:
[{"name":"Apple","count":2},{"name":"Banana","count":1},{"name":"Carrot","count":2},{"name":"Durian","count":1},{"name":"Eggplant","count":1}]. How can I achieve the correct output:
[{ name: "Apple", count: 2 }, { name: "Banana", count: 1 }, { name: "Carrot", count: 2 }, { name: "Durian", count: 1 }, { name: "Eggplant", count: 1 }] using the console.log() method?
<html>
<body>
<script>
var input = ["apple", "banana", "carrot", "durian", "eggplant", "apple", "carrot"];
var A = 0;//to count the number of apples
var B = 0;//to count the number of bananas
var C = 0;//to count the number of carrots
var D = 0;//to count the number of durians
var E = 0; //to count the number of eggplants
for (var i = 0; i < input.length; i++)
{
if (input[i] == "apple")
{
A += 1;
}
if (input[i] == "banana")
{
B += 1;
}
if (input[i] == "carrot")
{
C += 1;
}
if (input[i] == "durian")
{
D += 1;
}
if (input[i] == "eggplant")
{
E += 1;
}
}
let x1 = { name: 'Apple',
count: A };
let x2 = { name: 'Banana',
count: B };
let x3 = { name: 'Carrot',
count: C };
let x4 = { name: 'Durian',
count: D };
let x5 = { name: 'Eggplant',
count: E };
var output = [];
output.push(x1);
output.push(x2);
output.push(x3);
output.push(x4);
output.push(x5);
console.log("output = ", output);
document.getElementById('output').innerHTML = JSON.stringify(output);
</script>
</body>
</html>