Dane wejściowe to prosta tablica obiektów (contacts)

Wejście :

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

Wyjście chciałbym mieć:

[
  { 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 }
    ]
  }
];

Byłbym wdzięczny za poświęcony czas. Dziękuję.
Nawet pseudo-kod wystarczy.

0
Abhishek Mazumdar 19 grudzień 2019, 22:11

3 odpowiedzi

Musisz po prostu zmapować swoją tablicę w następujący sposób:

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}],
    };
  });

Nawiasem mówiąc, dane nie muszą być tablicą, jeśli jest tylko jeden element. data: {name: item.name, phone: item.phone} też działałoby dobrze.

1
Sylvain 19 grudzień 2019, 22:30

Możesz tymczasowo zebrać elementy do Map, a następnie wygenerować tablicę i sort() ją na końcu:

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);
0
tevemadar 20 grudzień 2019, 00:20
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 powinno odpowiadać oczekiwanym wynikom

0
Harvey Kadyanji 20 grudzień 2019, 00:31