0

I have an initial array1 =[{id:"0",a:"4",b:"6"},{id:"1",a:"r",b:"8"},{id:"2",a:"8",b:"9"}] I want another array that contains random elements from the intial array

randomArray=[{id:"0",a:"4",b:"6"},{id:"2",a:"8",b:"9"}] 

how can i do it?

grodzi
  • 5,633
  • 1
  • 15
  • 15
Maria-Elena
  • 127
  • 1
  • 11
  • your solution can be ```Math.random``` based. You have not described if the length of ```randomArray``` is less than the length of ```array1``` (otherwise you would have element repetition) – grodzi Oct 24 '19 at 07:37
  • 1
    Pls, write more detail: how length of intial array, randomArray – Ryan Nghiem Oct 24 '19 at 07:38

2 Answers2

2

You can use Array.prototype.filter and Math.random() like below;

const array1 =[{id:"0",a:"4",b:"6"},{id:"1",a:"r",b:"8"},{id:"2",a:"8",b:"9"}];
const filtered = array1.filter(() => Math.random() > 0.5);
console.log(filtered);

Note: The probability that every individual item is chosen is 50% in my solution.

Diamond
  • 3,470
  • 2
  • 19
  • 39
0

const random = (array, length) => array.sort(() => 0.5 - Math.random()).slice(0, length);

const mock = [
  { id: "0", a: "4", b: "6" },
  { id: "1", a: "r", b: "8" },
  { id: "2", a: "8", b: "9" },
  { id: "3", a: "8", b: "9" }
];

console.log(random(mock, 2))
console.log(random(mock, 3))
console.log(random(mock, 4))
Tolotra Raharison
  • 3,034
  • 1
  • 10
  • 15