How to Insert Element into Arrays At Specific Position

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 element into arrays at specific position?

array_slice() can be used to extract parts of the array, and the union array operator (+) can recombine the parts.

$res = array_slice($array, 0, 3, true) +
array("my_key" => "my_value") +
array_slice($array, 3, count($array)-3, true);

This example:

$array = array(
'zero' => '0',
'one' => '1',
'two' => '2',
'three' => '3',
);
$res = array_slice($array, 0, 3, true) +
array("my_key" => "my_value") +
array_slice($array, 3, count($array) - 1, true) ;
print_r($res);

gives:


Array
(
[zero] => 0
[one] => 1
[two] => 2
[my_key] => my_value
[three] => 3
)

Insert in array at specific location

I have corrected it:

arr_fla = [0,10,15,20,10,0,35,25,15,35,0,30,20,25,30,0]
arr_split = [5,7,8,15]
node = 5

for w in range(len(arr_split)):
arr_fla = np.insert(arr_fla, (w+1)*node-1, arr_split[w])
print(arr_fla)

'''
Output:
[ 0 10 15 20 5 10 0 35 25 7 15 35 0 30 8 20 25 30 0 15]
'''

In your code:

for v in arr_split:

This gets all the elements at once (in total w times), but you need just one element at a time. Thus you do not need an extra for loop.

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)

Inserting element in an array with position

This code should work.

#include <stdio.h>
#include <stdlib.h>

int main(void) {
int *array;

int size = 0;

int position, value;

printf("How many elements do you want to add? ");
scanf("%d", &size);

printf("\nEnter the values: \n");

// allocate the array
array = malloc(size * sizeof(int));

// insert the elements
for(int i = 0; i < size; i++) {
scanf("%d", &array[i]);
}

// print the array
for(int i = 0; i < size; i++) {
printf("%d ", array[i]);
}
printf("\n");

// read the position
printf("In which position you want to enter the element? ");
scanf("%d",&position);

// resize the array
size++;
array = realloc(array, size * sizeof(int));

// set the position to the true value
position--;

// read the value
printf("Which element do you want to insert? ");
scanf("%d", &value);

// move the elements
for(int i = size - 1; i > position; i--) {
array[i] = array[i - 1];
}

// insert the array
array[position] = value;

// print the value
for(int i = 0; i < size; i++) {
printf("%d ", array[i]);
}
printf("\n");
}

Of course you should implement some error handling. Especially for the alloc.

Insert new item in array on any position in PHP

You may find this a little more intuitive. It only requires one function call to array_splice:

$original = array( 'a', 'b', 'c', 'd', 'e' );
$inserted = array( 'x' ); // not necessarily an array, see manual quote

array_splice( $original, 3, 0, $inserted ); // splice in at position 3
// $original is now a b c x d e

If replacement is just one element it is not necessary to put array() around it, unless the element is an array itself, an object or NULL.

RETURN VALUE: To be noted that the function does not return the desired substitution. The $original is passed by reference and edited in place. See the expression array &$array with & in the parameters list .

How to insert item at certain positions in a multiple array loop

Perhaps I misunderstood something. I assumed the following:

:: The lengths of each array in the data array are the same.

:: You need to inject after each position, which will mess up a for loop that increase it's i(teration) variable.

:: There is always a Path and a Score in the first array.

:: You want to add a new value after each value, apart from the two above.

Solution

  1. Get the length of each array: data[0].length
  2. Loop from the end.
  3. Ignore last position.
  4. Ignore the first position
  5. Splice different value based on if it's the first item in the data array.

I loop over each value once, but I do it in the order of: 'Item5', 4, 6, 3, 3, 'Item4', 2, 5, 5, 2, 'Item3', ...

const data = [
['Path', 'Item1', 'Item2', 'Item3', 'Item4', 'Item5', 'Score'],
['/path-one', 1, 3, 2, 2, 4, 3],
['/path-two', 4, 5, 5, 5, 6, 3],
['/path-three', 5, 5, 3, 5, 3, 3],
['/path-four', 2, 3, 4, 2, 2, 3],
]

function mapArray(data) {
let secondToLastItem = data[0].length - 2; // 1 & 3
let FIRST_ITEM = 0; // 4

for (let index = secondToLastItem; index > FIRST_ITEM; index--) { // 2
for (let item = 0; item < data.length; item++) {
let injectedValue = (item == FIRST_ITEM) // 5
? {'role': 'annotation'}
: data[item][index];

data[item].splice(index + 1, 0, injectedValue);
}
}

return data;
}

console.log( mapArray(data) );

Inserting elements at specific positions in an array in a list in Python

It works like this:

import numpy as np

# need to take the indices based on the array before anything is inserted
J = [[4, 6, 8]]
C1 = [0]

A = [np.array([10. , 0.6382821834929432 , 0.5928417218382795 ,
0.5542698411479658 , 0.6677634679746701 , 0.8578897621707481 ,
0.6544597670890333 , 0.32706383813570833, 0.8966468940380192 ])]

A = np.insert(A[0], J[0], C1[0])

Output A:

array([10.        ,  0.63828218,  0.59284172,  0.55426984,  0.        ,
0.66776347, 0.85788976, 0. , 0.65445977, 0.32706384,
0. , 0.89664689])

Notice that A is not a list with a np.array anymore, it is just the np.array now.

EDIT
insert one at a time with given indices.

J = [[4, 7, 10]]
C1 = [0]

A = [np.array([10. , 0.6382821834929432 , 0.5928417218382795 ,
0.5542698411479658 , 0.6677634679746701 , 0.8578897621707481 ,
0.6544597670890333 , 0.32706383813570833, 0.8966468940380192 ])]

for elem in J[0]:
A = [np.insert(A[0], elem, C1[0])]


Related Topics



Leave a reply



Submit