2021年1月5日星期二

Problem solving i have a task for sorting with this small example but i cant get the idea anyhelp?

I have an array that comes from the backend sorted with this format below like this example :

    const Data = [      {          id: 1,          name: "jack"      },      {          id: 1,          name: "george"      },      {          id: 1,          name: "morries"      },      {          id: 2,          name: "abdo"      },      {          id: 2,          name: "ezz"      },      {          id: 3,          name: "mostafa"      },      {          id: 4,          name: "hamo"      },    ]  

I wanna make a new array with this format from the first array like the below code converting as not pushing the object with the same id in the new array but make it as an array property contain the all with the same id that's it

const newData = [      {          id:1,          names:["jack","george","morries"]      },      {          id:2,          names:["abdo","ezz"]      },      {          id:3,          names:["mostafa"]      },      {          id:4,          names:["hamo"]      }  ]  

so I'm thinking of this but I can't solve it

for (var i = 0; i <= Data.length; i++) {  if (newData.length > 0) {      for (var j = 0; j <= newData.length; j++) {          if (newData[j].id === Data[i].id) {              null          }          else newData.push(Data[i])      }  }  else newData.push(Data[i])  

}

https://stackoverflow.com/questions/65589296/problem-solving-i-have-a-task-for-sorting-with-this-small-example-but-i-cant-get January 06, 2021 at 10:16AM

没有评论:

发表评论