Abhishek Mazumdar
Abhishek Mazumdar

Reputation: 49

How to update array output

The input is a simple array of objects(contacts)

Input :

[
  { name: "Mohan", phone: xxxxxx },
  { name: "Ramanujan", phone: xxxxxx },
  { name: "Rabindranath", phone: xxxxxx },
  { name: "Satyajit", phone: xxxxxx },
  { name: "Subhash", phone: xxxxxx },
  { name: "Bahadur", phone: xxxxxx }
];

Output I would like to have:

[
  { title: "B", data: [{ name: "Bahadur", phone: xxxxxx }] },
  { title: "M", data: [{ name: "Mohan", phone: xxxxxx }] },
  {
    title: "R",
    data: [
      { name: "Ramanujan", phone: xxxxxx },
      { name: "Rabindranath", phone: xxxxxx }
    ]
  },
  {
    title: "S",
    data: [
      { name: "Satyajit", phone: xxxxxx },
      { name: "Subhash", phone: xxxxxx }
    ]
  }
];

I would appreciate the time you put in. Thank you.
Even the pseudo-code will do fine.

Upvotes: 0

Views: 84

Answers (3)

Harvey Kadyanji
Harvey Kadyanji

Reputation: 645

const myArray = [
    {name: 'Mohan', phone: 'xxxxxx'},
    {name: 'Ramanujan', phone: 'xxxxxx'},
    {name: 'Rabindranath', phone: 'xxxxxx'},
    {name: 'Satyajit', phone: 'xxxxxx'},
    {name: 'Subhash', phone: 'xxxxxx'},
    {name: 'Bahadur', phone: 'xxxxxx'},
  ];


 const data = {};

 myArray.forEach((obj) => {
   if(data[obj.name[0]]) {
        data[obj.name[0]].push(obj);
   } else {
     data[obj.name[0]] = [obj];
   }
 });

const arr = Object.entries(data).map((value) => {
  return {
    title: value[0],
    data: value[1],
  }
});

arr should match the intended results

Upvotes: 0

tevemadar
tevemadar

Reputation: 13195

You could temporarily collect items into a Map, then generate the array and sort() it at the end:

let original=[
    {name: "Mohan", phone: "xxxxxx"},
    {name: "Ramanujan", phone: "xxxxxx"},
    {name: "Rabindranath", phone: "xxxxxx"},
    {name: "Satyajit", phone: "xxxxxx"},
    {name: "Subhash", phone: "xxxxxx"},
    {name: "Bahadur", phone: "xxxxxx"}
];

let titlemap=new Map();
original.forEach(item=>{
  let title=item.name[0];
  if(!titlemap.has(title))
    titlemap.set(title,[]);
  titlemap.get(title).push(item);
});
let result=[];
titlemap.forEach((list,title)=>result.push({title:title,data:list}));
result.sort((a,b)=>a.title.charCodeAt(0)-b.title.charCodeAt(0));
console.log(result);

Upvotes: 0

Sylvain
Sylvain

Reputation: 529

you just have to map through your array like this:

const myArray = [
    {name: 'Mohan', phone: 'xxxxxx'},
    {name: 'Ramanujan', phone: 'xxxxxx'},
    {name: 'Rabindranath', phone: 'xxxxxx'},
    {name: 'Satyajit', phone: 'xxxxxx'},
    {name: 'Subhash', phone: 'xxxxxx'},
    {name: 'Bahadur', phone: 'xxxxxx'},
  ];
  const output = myArray.map(item => {
    return {
      title: item.name.charAt(0),
      data: [{name: item.name, phone: item.phone}],
    };
  });

By the way, data doesn't have to be an array if there's only one item. data: {name: item.name, phone: item.phone} would work fine too.

Upvotes: 1

Related Questions