0

listOfObjects = listOfObjects.concat(Array(10000000).fill({l: 50, b: 50, color: "#000000"}).map((s) => {
	s.x = Math.floor(Math.random() * (mapSquareSize));
	s.y = Math.floor(Math.random() * (mapSquareSize));
	return s;
}));

The listOfObjects array should have objects with the properties x,y, l, b and color. I have used the Array fill() function to set the l, b and color variables. I want the x and y co-ordinates to be unique for each object in ListOfObjects. However, the above code just gives the same random x and y co-ordinates to each Object.

I was using this for loop for this purpose, but a friend told me that a solution like this would be way more efficient.

// for (var i = 1 ; i <= 10000000 ; i++)
// {
//     var rock = new Object();
//     rock.x = Math.floor(Math.random() * (mapSquareSize)) + 0 ;
//     rock.y = Math.floor(Math.random() * (mapSquareSize)) + 0 ;
//     rock.l = 50 ;
//     rock.b = 50 ;
//     rock.color = "#000000";
//     listOfObjects.push(rock);
// }

5
  • 4
    When you use Array.fill() like that, every element in the array will be a reference to the exact same object. The .fill() approach is not going to be more efficient than your working simple for loop anyway. Commented Feb 18, 2019 at 15:22
  • Why would it be more efficient? Commented Feb 18, 2019 at 15:22
  • @Pointy So, is there a dynamic Array.fill() equivalent that would let me do this? Commented Feb 18, 2019 at 15:24
  • 1
    Your for loop looks fine to me; anything that operates on each element of an array is essentially doing the same amount of work. Commented Feb 18, 2019 at 15:25
  • 1
    The JS runtime will work more efficiently if you assign all of the properties in one go rather than one at a time. Commented Feb 18, 2019 at 15:31

1 Answer 1

3

There is Array.from:

 const result = Array.from({ length: 10000000 }, () => ({
   x: Math.floor(Math.random() * (mapSquareSize)),
   y: Math.floor(Math.random() * (mapSquareSize)),  
   l: 50,
   b: 50,
   color: "#000000",
}));

This works as expected and will create a new object during each iteration. It will do exactly the same as your for loop, it's just a bit more elegant (IMO).

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

1 Comment

I've never seen Array.from({ length: 10000000 }, () => {}) before, that's interesting. Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.