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?
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?
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.
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))