0

I am quite new to JavaScript professionally and I have encountered a situation where I need to give every item in a JavaScript array a unique id.

The array is very large so it cannot be done manually. Is there a simple way to do this? A simple numerical id for each would be superb. It is so that a PHP developer can easily manipulate the array and this is how he has requested it be done.

3
  • 3
    They index of each element in the array is a unique numerical id Commented Jan 24, 2012 at 19:13
  • 1
    Can you give more context? In a sense, the item's index in the array could serve as an id. But it depends on what the real intent here is. Commented Jan 24, 2012 at 19:14
  • What does your array look like? Commented Jan 24, 2012 at 19:14

2 Answers 2

5

Arrays in JS do have unique IDs - its index value.

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

Comments

0

Here are two ways of doing so:

Functional

array = /* Long or dynamically sized array of objects */

array.forEach(function (element, index) {
  element.uuid = index;
};

Iterative

array = /* Long or dynamically sized array of objects */

for (var ix = 0; ix < array.length; ix++) {
  array[ix].uuid = ix;
}

The index of the element of the array is being used as the UUID, since I'm not sure how you are generating the UUIDs, and that is the simplest. f you are sending the entire array through the server, you don't need a UUID based on index.

1 Comment

Hi everyone, thank you for your quick responses, I will experiment with these ideas in a few moments. Context wise, the project is a fairly simple game and the array is used to try the tile based game board. Each tile will need to be manipulated by the backend developer in one way or another. Here is how I am constructing the array: for (var row = startRow; row < rowCount; row++) { for (var col = startCol; col < colCount; col++) {//loop}

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.