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?

1
  • sounds like a function Commented Mar 5, 2019 at 3:44

4 Answers 4

2

That method is only on code.org https://docs.code.org/applab/insertItem/

But JS has a similar method you can use: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

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);

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

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);

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.