How to add the outout the random element from array and keep adding 1 by 1 in empty array?

20 Views Asked by At
   var arr1=[90,true,"hello",90,78,56,45,67,34,"apple","pinapple"]
    console.log(Math.floor(Math.random()*arr1.length))
    let indexNum1=Math.floor(Math.random()*arr1.length)
    console.log(arr[indexNum1])
    let getValue=arr[indexNum1]// get something 90 ||78 ||hello|| fumika
    let newarr=[];
   
    newarr.push(getValue)
    console.log(newarr)
  

// I do not know how to keep adding 1 by 1...until all the elements arr1 shows on newarr. Could you advise on me? Thank you

1

There are 1 best solutions below

1
RAllen On

You can move elements from the source array into destination by first adding them into the destination array and then removing them from the source, like so:

var arr1 = [90, true, "hello", 90, 78, 56, 45, 67, 34, "apple", "pinapple"];
console.log(arr1, arr1.length);
var newarr = [];
while (arr1.length > 0) {
  const index = Math.floor(Math.random() * arr1.length);
  newarr.push(arr1[index]);
  arr1.splice(index, 1);
}
console.log(newarr, newarr.length);

If you want to avoid removing elements from the source array, you can probably do something like this:

var arr1 = [90, true, "hello", 90, 78, 56, 45, 67, 34, "apple", "pinapple"];
console.log(arr1, arr1.length);
var newarr = [];
arr1.forEach(el => {
  newarr.splice(Math.floor(Math.random() * newarr.length), 0, el);
});
console.log(newarr, newarr.length);

With this approach, you insert elements randomly into the new array. I just came up with this approach, but I'm not sure it will give you "real" randomness.

Please let me know if this helps.