0

I would like to know how to shuffle the order of array of objects in javascript.

The order of object inside array should not repeat, how to shuffle the objects in array

var obj=[
  {id:1, name: "xyz"},
  {id:2, name: "abc"},
  {id:3, name: "zen"}
]

Expected Output
//should have change in order without repetition
[
  {id:2, name: "xyz"},
  {id:1, name: "abc"},
  {id:3, name: "zen"}
]

[
  {id:3, name: "xyz"},
  {id:2, name: "abc"},
  {id:1, name: "zen"}
]

var result = obj.map(e=> Math.floor(Math.random() * e - 0.5);

ved
  • 167
  • 9
  • 3
    Duplicate: [How to randomize (shuffle) a JavaScript array?](https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array) –  Jul 16 '21 at 12:52

1 Answers1

0

You can randomly pick objects, remove them from the container and put them into another container.

const obj = [
  {id:1, name: "xyz"},
  {id:2, name: "abc"},
  {id:3, name: "zen"}
];
const result = [];

while (obj.length) {
  const index = Math.floor(Math.random() * obj.length);
  result.push(obj.splice(index, 1)[0]);
}

console.log(result);