Add An Element At The End Of A List Of Objects In JavaScript
I have a list like this as an input: {value: 1, rest: {value: 2, rest: null}} I want to add an element to the list and place it in order to have this output: {value: 1, rest: {val
Solution 1:
You can use for
loop here and when i is last object or when rest is null
add new object and break loop.
var obj = {value: 1, rest: {value: 2, rest: null}}
function add(elem, list) {
for (var i = obj; i; i = i.rest) {
if (i.rest == null) {
i.rest = { value: elem,rest: null}
break;
}
}
}
add(3, obj)
console.log(obj)
Solution 2:
Try this. I made a recursive function.
function prepend(elem, list){
if (list.rest == null)
list.rest = {value:elem, rest:null};
else
prepend(elem, list.rest);
return list;
}
This function can be used in all cases.
Solution 3:
function append(list, item){
if(list.rest == null)
list.rest = item;
else
append(list.rest, item)
}
Solution 4:
What you can do is use an array of objects and use append()
in the array
Solution 5:
You could iterate through the rest
objects and assign then the new object to the last.
function prepend(elem, list) {
var object = list;
while (object.rest) {
object = object.rest;
}
object.rest = { value: elem, rest: null };
return list;
}
console.log(prepend(3, { value: 1, rest: { value: 2, rest: null } }));
Post a Comment for "Add An Element At The End Of A List Of Objects In JavaScript"