I have a function that has been made to manipulate and create an object array and add a position
key to each item within the array, but it seems to not be working properly at all...
My function:
var fillQueue = function(choices, currentQueue) {
var choice, i, positionInQueue, previousTitle, resultQueue;
resultQueue = [];
previousTitle = "";
i = 0;
while (i < 10) {
positionInQueue = i + 1;
console.log('Adding song to position ' + positionInQueue);
if (currentQueue[i]) {
previousTitle = currentQueue[i].title;
currentQueue[i].position = positionInQueue;
resultQueue.push(currentQueue[i]);
} else {
choice = choices[Math.floor(Math.random() * choices.length)];
if (choice.title !== previousTitle) {
previousTitle = choice.title;
choice.position = positionInQueue;
resultQueue.push(choice);
} else {
choice = choices[Math.floor(Math.random() * choices.length)];
previousTitle = choice.title;
choice.position = positionInQueue;
resultQueue.push(choice);
}
}
i++;
}
return resultQueue;
};
If this is called correctly, substituting in values for choices
and currentQueue
(currentQueue
can also be an empty array) like below, the function returns an array, which is intended, but screws around with the position
keys on each object within it for some reason.
var test = fillQueue([ {title: '1'}, {title: '2'}, {title: '3'}, {title: '4'} ], [ { title: '5', position: 1 } ]);
The above variable will contain this:
[ { title: '5', position: 1 },
{ title: '1', position: 9 },
{ title: '3', position: 7 },
{ title: '1', position: 9 },
{ title: '2', position: 10 },
{ title: '2', position: 10 },
{ title: '3', position: 7 },
{ title: '1', position: 9 },
{ title: '1', position: 9 },
{ title: '2', position: 10 } ]
As you can see, it's not adding the position
s correctly into each object. Each object within the returned array should have a position
of i + 1
, but instead it seems to be some random number from 1 to 10 - some of the objects even have the same position
.
I have tried:
- Renaming
position
to something else, in case it was something that was already being used by JavaScript - Making sure that the correct
position
is being added to the object before and after.push
ing it into the array.
This is making me really confused. Your help would be appreciated.
choice.position
, all instances of that choice get the same "position" value, e.g. all the choices with "Title:1" will have the same position because they all reference the same object. You need to create a copy of the choice, update its position and push the copy into the array. – RobG Feb 18 at 6:43position
property equal toi + 1
. – deansheather Feb 18 at 6:44