I have an array of objects. These objects have a property that is also an array. I want to insert a new value into my array of objects. It has to be sequential in that I always want to add the value to the first objects array but if there is an item in the first objects array already, then I want to move it to the second to make room for the new item.
the result I am getting is the first two objects have the newest value in the list, and the last object has the first added value. The intended result is for the first object in the array to have a list with a value of ‘item2’, the next object in the array to have a list with the value of ‘item1’ and the last object to have an empty list until I add another item.
Thank you for the help.
function addItem(arr, item) {
let current = 0;
//if first object list is empty add the item
if(!arr[0].list.length){
arr[current].list.push(item);
return
}
while (current < arr.length) {
//check the current objects list is not empty
if(arr[current].list.length != 0){
//check if there is a next object in the array and it has an item in it's list
if(arr[current + 1] && !arr[current + 1].list.length){
//if there is a next object and it does not have an item in it's list
//remove the current item in current list
let move_item = arr[current].list.shift();
//add the item to the next object in the array
arr[current + 1].list.push(move_item);
//add the new item to the current object in the array
arr[current].list.push(item);
}
}
console.log(arr[current]);
current++;
}
}
// Example usage
let item = 'item1';
let item2 = 'item2';
const myArr = [
{name:'one', list:[]},
{name:'two', list:[]},
{name:'three', list:[]}
];
addItem(myArr, item);
addItem(myArr, item2);
3
Answers
You could iterate from the end and move all items to the end of the array.
Locate the first item in
arr
with an empty list. Then, use afor
loop to shift right the contents of all lists preceeding it.Finally, add the new item into the first
arr
list (which will have been emptied by thefor
loop)You can iterate array and keep the current item to be shifted in a temp
next
var: