0

i have question about array, for example i have an array of object, like this

const data = [
  {
    level: 1,
    name: "Naruto",
  },
  {
    level: 2,
    name: "Dragon",
  },
  {
    level: 2,
    name: "Ball",
  },
  {
    level: 3,
    name: "Sasuke",
  },
] 

Now i want to create new array base on level , mean that after format it will look like this:

[
  [
    {
      name: "naruto"
    }
  ],
  [
    {
      name: "Ball"
    },
    { name: "Dragon" }
  ],
  [
    {name:"Sasuke"}
  ]
];

How can i do this, thanks you guys

5
  • 1
    what have you tried so far? look into groupBy commands in javascript, they are going to give similar results, which you can manipulate into your answer. Commented Mar 17, 2022 at 3:17
  • Thanks for your answer, I tried with maps but it return each element with seperate array Commented Mar 17, 2022 at 3:20
  • 1
    try this : developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… , it will not give you the exact result, however you can manipulate the result from the groupBy to the result that you require Commented Mar 17, 2022 at 3:22
  • I tried but it said groupBy not a function Commented Mar 17, 2022 at 3:29
  • 1
    oh, then your js must be slightly outdated, it was only recently introduced, here you go, use these implementation instead, edisondevadoss.medium.com/… Commented Mar 17, 2022 at 3:33

1 Answer 1

1

I used a loop to handle your case

currentLevel - 1 is mapped with the index of the result's array

const data = [{
    level: 1,
    name: "Naruto",
  },
  {
    level: 2,
    name: "Dragon",
  },
  {
    level: 2,
    name: "Ball",
  },
  {
    level: 3,
    name: "Sasuke",
  },
];

let result = []
for (const currentValue of data) {

  const currentLevel = currentValue.level

  if (!result[currentLevel - 1]) {
    result[currentLevel - 1] = []
  }

  result[currentLevel - 1].push({
     name: currentValue.name
  })
}

//it's followed by index, the result will have some `undefined` if your levels have gaps. You can comment it out, if you want to keep `undefined` values
result = result.filter(item => item)

console.log({
  result
})

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.