How to Insert an Item into an Array At a Specific Index (JavaScript)

How to insert an item into an array at a specific index (JavaScript)

You want the splice function on the native array object.

arr.splice(index, 0, item); will insert item into arr at the specified index (deleting 0 items first, that is, it's just an insert).

In this example we will create an array and add an element to it into index 2:

var arr = [];
arr[0] = "Jani";
arr[1] = "Hege";
arr[2] = "Stale";
arr[3] = "Kai Jim";
arr[4] = "Borge";

console.log(arr.join()); // Jani,Hege,Stale,Kai Jim,Borge
arr.splice(2, 0, "Lene");
console.log(arr.join()); // Jani,Hege,Lene,Stale,Kai Jim,Borge

How to insert into an array at a specific index?

splice operates on the array in place returning an array of deleted elements, or an empty array if none have been deleted. So while you can chain the method in those instances it won't work for your example.

const num = 1234;
const arr = num.toString().split('')
arr.splice(2, 0, ':');
const str = arr.join('');
console.log(str)

How to push to an array in a particular position?

array = [4,5,9,6,2,5]

#push 0 to position 1
array.splice(1,0,0)

array = [4,0,5,9,6,2,5]

#push 123 to position 1
array.splice(1,0,123)

array = [4,123,0,5,9,6,2,5]

js: add element at the start of an array

Ok,

let arr = [1,2]
let foo={bar:true}
arr=[foo].concat(arr)

also what you already know works

arr=[foo, ...arr]

That's it

In Javascript how do I create a secondary array in a specific index?

You could assign the concatinated values.

const
addAt = (array, value, index) => array[index] = [].concat(array[index], value),
array = [5, 2, 1, 2];

addAt(array, 8, 1);
console.log(array)

addAt(array, 3, 1);
console.log(array)
.as-console-wrapper { max-height: 100% !important; top: 0; }

JS insert into array at specific index

Well, thats pretty easy. Assuming you have an array with 5 objects inside and you want to insert a string at index 2 you can simply use javascripts array splice method:

var array = ['foo', 'bar', 1, 2, 3],
insertAtIndex = 2,
stringToBeInserted = 'someString';

// insert string 'someString' into the array at index 2
array.splice( insertAtIndex, 0, stringToBeInserted );

Your result will be now:

['foo', 'bar', 'someString', 1, 2, 3]

FYI: The push() method you used just adds new items to the end of an array (and returns the new length)

How to insert elements into specific index in a 2D array in javascript?

Simple fix on your problem is that just changing your manner to set initial value of statusOrderInfo and use Array.from instead of Array.fill like this:

let statusOrderInfo = Array.from({length: Object.keys(statusOrder).length}, ()=> []);

another solution is set initiali value of statusOrderInfo by empty array, and then in your for loop, after you get the index of current object based on status value, you can check if statusIndex already exist in the statusOrderInfo or not, like this:

const statusOrder = {"Reachable": 0, "Busy": 1, "Unknown": 2}
let statusOrderInfo = [];
for(let i=0; i< tableData.length; i++) {
const status = tableData[i]["Status"].trim()
const statusIndex = statusOrder[status];
if(statusOrderInfo[statusIndex]) statusOrderInfo[statusIndex].push(tableData[i]);
else statusOrderInfo[statusIndex] = [ tableData[i] ]
}
console.log(statusOrderInfo);

another solution, is to use reduce method on array, like this:

const tableData = [{

"Location": "London",
"Status": "Unknown"
},
{

"Location": "Delhi",
"Status": "Reachable"
},
{

"Location": "Berlin",
"Status": "Unknown"
},
{

"Location": "Tokyo",
"Status": "Busy"
},
];
const statusOrder = {"Reachable": 0, "Busy": 1, "Unknown": 2}
const result = tableData.reduce((acc, cur) => {
const index = statusOrder[cur.Status];
if (acc[index]) acc[index].push(cur);
else acc[index] = [cur]
return acc;
}, []);
console.log(result)


Related Topics



Leave a reply



Submit