1

I have the following object:

var arrayOfStuff= {};
arrayOfStuff.chapter = [];

for (var k = 0; k < array2.length; k++) {
    arrayOfStuff.chapter.push({"title": array2[k][1], "page": array2[k][2]}) 
}

How can I get the ability to delete a record from the arrayOfStuff, without leaving a blank record behind? I've tried load of stuff, and not posting them here because I know they are wrong!

i.e. i have

NameA, 2
NameB, 7
NameC, 11
NameD, 15
NameE, 20

and I call something like arrayOfStuff.chapter[2].remove(); to get:

NameA, 2
NameB, 7
NameD, 15
NameE, 20

PS: On a side question, what's the correct name for this type of object? I would associate it as a multidimensional array of some sort.

4 Answers 4

2

To remove an element from an array, you can use splice(). The first parameter is the index of the first item you want to remove, the second parameter is the number of items you want to remove. The following example removes element 2.

arrayOfStuff.chapter.splice(2, 1);

This function works for arrays. If you want to remove a property from an object, you can use the delete keyword. If you use delete on an array, it leaves behind an empty element, though. The following example removes the property chapter from your arrayOfStuff object.

delete arrayOfStuff.chapter;

To answer your side question: arrayOfStuff is simply an object. It has a property called chapter, which is an array. There is no special name for this kind of construct.

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

Comments

1

You can use splice():

arrayOfStuff.chapter.splice(2,1);
// 2 : start index
// 1 : how many

1 Comment

best answer considering you included the '.chapter' part.
0

Use the splice method to remove the item from the array.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

Comments

0

Add items to the array: var fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.splice(2,0,"Lemon","Kiwi");

The result of fruits will be: Banana,Orange,Lemon,Kiwi,Apple,Mango

At position 2, remove 2 items: var fruits = ["Banana", "Orange", "Apple", "Mango"];

fruits.splice(2,2);

The result of fruits will be: Banana,Orange

Comments

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.