skip to Main Content

How to get output using javascript ?????

const arr = ["Barath", "Babu", "Prakash", "Praveen", "Arun"]

output = {b: ["Barath", "Babu"], p:["Prakash", "Praveen"] , a:["Arun"]}

2

Answers


  1. 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:

    const arr = ["Barath", "Babu", "Prakash", "Praveen", "Arun"];
    
    const output = arr.reduce((result, name) => {
      const firstLetter = name[0].toLowerCase();
      result[firstLetter] = result[firstLetter] || [];
      result[firstLetter].push(name);
      return result;
    }, {});
    
    console.log(output);

    You can test this here, just copy paste code https://www.programiz.com/javascript/online-compiler/

    Login or Signup to reply.
  2. If I understand your intentions right, this should work:

    const arr = ["Barath", "Babu", "Prakash", "Praveen", "Arun"];
    let output = {};
    arr.forEach(element => {
      const letter = element.charAt(0).toLowerCase();
      if (output[letter] === undefined) output[letter] = [];
      output[letter].push(element);
    });
    
    console.log(output);

    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 notation object.prop. This allows us to access properties dynamically without needing to know them beforehand.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search