0

I'm learning about arrays in Code.org.

So there are methods like insertItem(list, index, item) in code.org, but as I read many books about arrays in javaScript, none of them talked about the insertItem Method.

I wanted to know if insertItem is generic to JS or is it just specifically made for the code.org platform?

Jack Bashford
44.3k11 gold badges56 silver badges84 bronze badges
asked Mar 5, 2019 at 3:36
1
  • sounds like a function Commented Mar 5, 2019 at 3:44

4 Answers 4

2
answered Mar 5, 2019 at 3:39
Sign up to request clarification or add additional context in comments.

Comments

2

insertItem() is purely code.org

https://docs.code.org/applab/insertItem/

To do this in regular javascript, you would:

  1. If you wanted to insert the item into the end of the array, you would use .push()

var array = [0, 1, 2];
console.log(array);
array.push("item");
console.log(array);

  1. If you wanted to replace an item in the array (in which you know the index), you would use array[index] = item;

var array = [0, 1, 2];
console.log(array);
array[1] = "item";
console.log(array);

  1. If you wanted to replace an item in an array by knowing the value, but not the index, you would use array[array.indexOf(value)] = item;

var array = [0, 1, 2];
console.log(array);
array[array.indexOf(1)] = "item";
console.log(array);

  1. Finally, if you wanted to insert an item into the array, you would use .splice(). To insert an item after index 2, you would use array.splice(2, 0, item).

var array = [0, 1, 2];
console.log(array);
array.splice(1, 0, "item");
console.log(array);

Code.org probably uses the following function to make life easier for you:

var array = [0, 1, 2];
function insertItem(list, index, item) {
 list.splice(index, 0, item);
 return list;
}
console.log(array);
array = insertItem(array, 1, "item");
console.log(array);

answered Mar 5, 2019 at 3:48

Comments

1

There is no method by name insertItem for Array in javascript. Also it seems insertItem(list, index, item) is a function and it accepts three arguments.

You can get list of javascript array methods in this link

answered Mar 5, 2019 at 3:39

Comments

1

There's no JavaScript function named insertItem - however, there's an almost identical method named splice - syntax like list.splice(index, 0, item):

var list = [1, 2, 4];
var item = 3;
var index = 2;
list.splice(index, 0, item);
console.log(list);

answered Mar 5, 2019 at 3:47

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.