How to get output using javascript ?????
const arr = ["Barath", "Babu", "Prakash", "Praveen", "Arun"]
output = {b: ["Barath", "Babu"], p:["Prakash", "Praveen"] , a:["Arun"]}
How to get output using javascript ?????
const arr = ["Barath", "Babu", "Prakash", "Praveen", "Arun"]
output = {b: ["Barath", "Babu"], p:["Prakash", "Praveen"] , a:["Arun"]}
2
Answers
You can achieve this by iterating over the array and creating an object where the keys are the first letters of each name and the values are arrays containing names starting with that letter.
Here’s how you can do this:
You can test this here, just copy paste code https://www.programiz.com/javascript/online-compiler/
If I understand your intentions right, this should work:
We’re using a function that is called for each element in your source array.
We then extract the first letter of each element, converting it to lowercase.
We check, whether the output object already has an element of that letter, if not, we generate one as an empty array.
Finally we push our element into this array which then exists for every first letter in the input array.
Note the bracket notation
object[prop]
to access object properties instead of the dot notationobject.prop
. This allows us to access properties dynamically without needing to know them beforehand.