1

Say I have the following array:

const months = ['January', 'February', 'March', 'April', 'June'];

And I want to add the item December at position 11. From what I know I would do:

months.splice(11, 0, "December");

I would like it to be added in position 11 and positions 5 to 10 to be "null" or "undefined". However when I do:

months.indexOf("December")

I get a result of 5 and printing the array returns December as the last position right after June.

Is there a way to add this item at the specified position?

Thanks

2 Answers 2

1

Just take the index and assign the value. Unset items are undefined, because you got a sparse array.

const months = ['January', 'February', 'March', 'April', 'June'];

months[11] = "December";

console.log(months.indexOf("December"));
console.log(months);

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

Comments

0

One more way to do is increase the array length and push the element.

const months = ['January', 'February', 'March', 'April', 'June'];

months.length = 11;
months.push("December");

console.log(months.indexOf("December"));
console.log(months.findIndex(x => x === "December"));
console.log(months);

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.