Removing elements from array after pulling data from firebase - javascript

I am pulling an object from firebase converting it to an array then doing remove element operation on it but there is some strange behaviour:
this.players = this.db.object('arena/players').valueChanges();
this.players.subscribe(players =>{
console.log(players);
this.playersarray= Object.keys(players).map(key => ({ key, value: players[key] }));
console.log(this.playersarray);
console.log(this.playersarray.length);
for(var i =0;i<this.playersarray.length;i++){
if(this.playersarray[i].value != "waiting"){
console.log(this.playersarray[i].value+"deleting");
this.playersarray.splice(i,1);
}
}
console.log(this.playersarray);
});
This is console:
I am trying to remove elements which value are not equal to waiting.So in this case im expecting to remove engincan,lifesuxtr and get last console.log as only someotheruser,someuser
but lifesuxtr is not removed ??? only engincan removed ?

You can use Array.filter operator to iterate over the Array and filter our the relevant results, example:
const arr = [1, 2, 3, 4, 5];
const result = arr.filter((item) => item % 2 === 1);
console.log(result);

When you remove the items from the array, the index of all following items shift down. Because you're removing an item, your loop skips an item.
// Array starts as:
// 0 1 2 3
// ['a', 'b', 'c', 'd']
// Loop 1: Index 0, item 'a'. Matches test, remove it.
// Array becomes:
// 0 1 2
// ['b', 'c', 'd']
// Loop 2: Index 1, item 'c'.
// Loop 3: Index 2, item 'd'.
The quickest fix is to change the index by subtracting one from it but that's can get hard to keep track of quickly. I'd recommend using the Array.filter() method.
this.playersarray = this.playersarray.filter(function(player) {
return player.value != 'waiting'
})

Simple way to remove array element by value.
var playersarray = {
"name": "John",
"age": 30,
"cars": "Ford"
};
for(value in playersarray){
if(playersarray[value] != "Ford"){
delete playersarray[value]; //deleting array elements if no 'Ford'
}
}
console.log(playersarray);
Output: {cars:"Ford"}

Related

Javascript delete object items leaves null traces [duplicate]

What is the difference between using the delete operator on the array element as opposed to using the Array.splice method?
For example:
myArray = ['a', 'b', 'c', 'd'];
delete myArray[1];
// or
myArray.splice (1, 1);
Why even have the splice method if I can delete array elements like I can with objects?
delete will delete the object property, but will not reindex the array or update its length. This makes it appears as if it is undefined:
> myArray = ['a', 'b', 'c', 'd']
["a", "b", "c", "d"]
> delete myArray[0]
true
> myArray[0]
undefined
Note that it is not in fact set to the value undefined, rather the property is removed from the array, making it appear undefined. The Chrome dev tools make this distinction clear by printing empty when logging the array.
> myArray[0]
undefined
> myArray
[empty, "b", "c", "d"]
myArray.splice(start, deleteCount) actually removes the element, reindexes the array, and changes its length.
> myArray = ['a', 'b', 'c', 'd']
["a", "b", "c", "d"]
> myArray.splice(0, 2)
["a", "b"]
> myArray
["c", "d"]
Array.remove() Method
John Resig, creator of jQuery created a very handy Array.remove method that I always use it in my projects.
// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
var rest = this.slice((to || from) + 1 || this.length);
this.length = from < 0 ? this.length + from : from;
return this.push.apply(this, rest);
};
and here's some examples of how it could be used:
// Remove the second item from the array
array.remove(1);
// Remove the second-to-last item from the array
array.remove(-2);
// Remove the second and third items from the array
array.remove(1,2);
// Remove the last and second-to-last items from the array
array.remove(-2,-1);
John's website
Because delete only removes the object from the element in the array, the length of the array won't change. Splice removes the object and shortens the array.
The following code will display "a", "b", "undefined", "d"
myArray = ['a', 'b', 'c', 'd']; delete myArray[2];
for (var count = 0; count < myArray.length; count++) {
alert(myArray[count]);
}
Whereas this will display "a", "b", "d"
myArray = ['a', 'b', 'c', 'd']; myArray.splice(2,1);
for (var count = 0; count < myArray.length; count++) {
alert(myArray[count]);
}
I stumbled onto this question while trying to understand how to remove every occurrence of an element from an Array. Here's a comparison of splice and delete for removing every 'c' from the items Array.
var items = ['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd'];
while (items.indexOf('c') !== -1) {
items.splice(items.indexOf('c'), 1);
}
console.log(items); // ["a", "b", "d", "a", "b", "d"]
items = ['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd'];
while (items.indexOf('c') !== -1) {
delete items[items.indexOf('c')];
}
console.log(items); // ["a", "b", undefined, "d", "a", "b", undefined, "d"]
​
From Core JavaScript 1.5 Reference > Operators > Special Operators > delete Operator :
When you delete an array element, the
array length is not affected. For
example, if you delete a[3], a[4] is
still a[4] and a[3] is undefined. This
holds even if you delete the last
element of the array (delete
a[a.length-1]).
As stated many times above, using splice() seems like a perfect fit. Documentation at Mozilla:
The splice() method changes the content of an array by removing existing elements and/or adding new elements.
var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
myFish.splice(2, 0, 'drum');
// myFish is ["angel", "clown", "drum", "mandarin", "sturgeon"]
myFish.splice(2, 1);
// myFish is ["angel", "clown", "mandarin", "sturgeon"]
Syntax
array.splice(start)
array.splice(start, deleteCount)
array.splice(start, deleteCount, item1, item2, ...)
Parameters
start
Index at which to start changing the array. If greater than the length of the array, actual starting index will be set to the length of the array. If negative, will begin that many elements from the end.
deleteCount
An integer indicating the number of old array elements to remove. If deleteCount is 0, no elements are removed. In this case, you should specify at least one new element. If deleteCount is greater than the number of elements left in the array starting at start, then all of the elements through the end of the array will be deleted.
If deleteCount is omitted, deleteCount will be equal to (arr.length - start).
item1, item2, ...
The elements to add to the array, beginning at the start index. If you don't specify any elements, splice() will only remove elements from the array.
Return value
An array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned.
[...]
splice will work with numeric indices.
whereas delete can be used against other kind of indices..
example:
delete myArray['text1'];
It's probably also worth mentioning that splice only works on arrays. (Object properties can't be relied on to follow a consistent order.)
To remove the key-value pair from an object, delete is actually what you want:
delete myObj.propName; // , or:
delete myObj["propName"]; // Equivalent.
delete Vs splice
when you delete an item from an array
var arr = [1,2,3,4]; delete arr[2]; //result [1, 2, 3:, 4]
console.log(arr)
when you splice
var arr = [1,2,3,4]; arr.splice(1,1); //result [1, 3, 4]
console.log(arr);
in case of delete the element is deleted but the index remains empty
while in case of splice element is deleted and the index of rest elements is reduced accordingly
delete acts like a non real world situation, it just removes the item, but the array length stays the same:
example from node terminal:
> var arr = ["a","b","c","d"];
> delete arr[2]
true
> arr
[ 'a', 'b', , 'd', 'e' ]
Here is a function to remove an item of an array by index, using slice(), it takes the arr as the first arg, and the index of the member you want to delete as the second argument. As you can see, it actually deletes the member of the array, and will reduce the array length by 1
function(arr,arrIndex){
return arr.slice(0,arrIndex).concat(arr.slice(arrIndex + 1));
}
What the function above does is take all the members up to the index, and all the members after the index , and concatenates them together, and returns the result.
Here is an example using the function above as a node module, seeing the terminal will be useful:
> var arr = ["a","b","c","d"]
> arr
[ 'a', 'b', 'c', 'd' ]
> arr.length
4
> var arrayRemoveIndex = require("./lib/array_remove_index");
> var newArray = arrayRemoveIndex(arr,arr.indexOf('c'))
> newArray
[ 'a', 'b', 'd' ] // c ya later
> newArray.length
3
please note that this will not work one array with dupes in it, because indexOf("c") will just get the first occurance, and only splice out and remove the first "c" it finds.
If you want to iterate a large array and selectively delete elements, it would be expensive to call splice() for every delete because splice() would have to re-index subsequent elements every time. Because arrays are associative in Javascript, it would be more efficient to delete the individual elements then re-index the array afterwards.
You can do it by building a new array. e.g
function reindexArray( array )
{
var result = [];
for( var key in array )
result.push( array[key] );
return result;
};
But I don't think you can modify the key values in the original array, which would be more efficient - it looks like you might have to create a new array.
Note that you don't need to check for the "undefined" entries as they don't actually exist and the for loop doesn't return them. It's an artifact of the array printing that displays them as undefined. They don't appear to exist in memory.
It would be nice if you could use something like slice() which would be quicker, but it does not re-index. Anyone know of a better way?
Actually, you can probably do it in place as follows which is probably more efficient, performance-wise:
reindexArray : function( array )
{
var index = 0; // The index where the element should be
for( var key in array ) // Iterate the array
{
if( parseInt( key ) !== index ) // If the element is out of sequence
{
array[index] = array[key]; // Move it to the correct, earlier position in the array
++index; // Update the index
}
}
array.splice( index ); // Remove any remaining elements (These will be duplicates of earlier items)
},
you can use something like this
var my_array = [1,2,3,4,5,6];
delete my_array[4];
console.log(my_array.filter(function(a){return typeof a !== 'undefined';})); // [1,2,3,4,6]
The difference can be seen by logging the length of each array after the delete operator and splice() method are applied. For example:
delete operator
var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple'];
delete trees[3];
console.log(trees); // ["redwood", "bay", "cedar", empty, "maple"]
console.log(trees.length); // 5
The delete operator removes the element from the array, but the "placeholder" of the element still exists. oak has been removed but it still takes space in the array. Because of this, the length of the array remains 5.
splice() method
var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple'];
trees.splice(3,1);
console.log(trees); // ["redwood", "bay", "cedar", "maple"]
console.log(trees.length); // 4
The splice() method completely removes the target value and the "placeholder" as well. oak has been removed as well as the space it used to occupy in the array. The length of the array is now 4.
Performance
There are already many nice answer about functional differences - so here I want to focus on performance. Today (2020.06.25) I perform tests for Chrome 83.0, Safari 13.1 and Firefox 77.0 for solutions mention in question and additionally from chosen answers
Conclusions
the splice (B) solution is fast for small and big arrays
the delete (A) solution is fastest for big and medium fast for small arrays
the filter (E) solution is fastest on Chrome and Firefox for small arrays (but slowest on Safari, and slow for big arrays)
solution D is quite slow
solution C not works for big arrays in Chrome and Safari
function C(arr, idx) {
var rest = arr.slice(idx + 1 || arr.length);
arr.length = idx < 0 ? arr.length + idx : idx;
arr.push.apply(arr, rest);
return arr;
}
// Crash test
let arr = [...'abcdefghij'.repeat(100000)]; // 1M elements
try {
C(arr,1)
} catch(e) {console.error(e.message)}
Details
I perform following tests for solutions
A
B
C
D
E (my)
for small array (4 elements) - you can run test HERE
for big array (1M elements) - you can run test HERE
function A(arr, idx) {
delete arr[idx];
return arr;
}
function B(arr, idx) {
arr.splice(idx,1);
return arr;
}
function C(arr, idx) {
var rest = arr.slice(idx + 1 || arr.length);
arr.length = idx < 0 ? arr.length + idx : idx;
arr.push.apply(arr, rest);
return arr;
}
function D(arr,idx){
return arr.slice(0,idx).concat(arr.slice(idx + 1));
}
function E(arr,idx) {
return arr.filter((a,i) => i !== idx);
}
myArray = ['a', 'b', 'c', 'd'];
[A,B,C,D,E].map(f => console.log(`${f.name} ${JSON.stringify(f([...myArray],1))}`));
This snippet only presents used solutions
Example results for Chrome
Why not just filter? I think it is the most clear way to consider the arrays in js.
myArray = myArray.filter(function(item){
return item.anProperty != whoShouldBeDeleted
});
They're different things that have different purposes.
splice is array-specific and, when used for deleting, removes entries from the array and moves all the previous entries up to fill the gap. (It can also be used to insert entries, or both at the same time.) splice will change the length of the array (assuming it's not a no-op call: theArray.splice(x, 0)).
delete is not array-specific; it's designed for use on objects: It removes a property (key/value pair) from the object you use it on. It only applies to arrays because standard (e.g., non-typed) arrays in JavaScript aren't really arrays at all*, they're objects with special handling for certain properties, such as those whose names are "array indexes" (which are defined as string names "...whose numeric value i is in the range +0 ≤ i < 2^32-1") and length. When you use delete to remove an array entry, all it does is remove the entry; it doesn't move other entries following it up to fill the gap, and so the array becomes "sparse" (has some entries missing entirely). It has no effect on length.
A couple of the current answers to this question incorrectly state that using delete "sets the entry to undefined". That's not correct. It removes the entry (property) entirely, leaving a gap.
Let's use some code to illustrate the differences:
console.log("Using `splice`:");
var a = ["a", "b", "c", "d", "e"];
console.log(a.length); // 5
a.splice(0, 1);
console.log(a.length); // 4
console.log(a[0]); // "b"
console.log("Using `delete`");
var a = ["a", "b", "c", "d", "e"];
console.log(a.length); // 5
delete a[0];
console.log(a.length); // still 5
console.log(a[0]); // undefined
console.log("0" in a); // false
console.log(a.hasOwnProperty(0)); // false
console.log("Setting to `undefined`");
var a = ["a", "b", "c", "d", "e"];
console.log(a.length); // 5
a[0] = undefined;
console.log(a.length); // still 5
console.log(a[0]); // undefined
console.log("0" in a); // true
console.log(a.hasOwnProperty(0)); // true
* (that's a post on my anemic little blog)
Others have already properly compared delete with splice.
Another interesting comparison is delete versus undefined: a deleted array item uses less memory than one that is just set to undefined;
For example, this code will not finish:
let y = 1;
let ary = [];
console.log("Fatal Error Coming Soon");
while (y < 4294967295)
{
ary.push(y);
ary[y] = undefined;
y += 1;
}
console(ary.length);
It produces this error:
FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory.
So, as you can see undefined actually takes up heap memory.
However, if you also delete the ary-item (instead of just setting it to undefined), the code will slowly finish:
let x = 1;
let ary = [];
console.log("This will take a while, but it will eventually finish successfully.");
while (x < 4294967295)
{
ary.push(x);
ary[x] = undefined;
delete ary[x];
x += 1;
}
console.log(`Success, array-length: ${ary.length}.`);
These are extreme examples, but they make a point about delete that I haven't seen anyone mention anywhere.
function remove_array_value(array, value) {
var index = array.indexOf(value);
if (index >= 0) {
array.splice(index, 1);
reindex_array(array);
}
}
function reindex_array(array) {
var result = [];
for (var key in array) {
result.push(array[key]);
}
return result;
}
example:
var example_arr = ['apple', 'banana', 'lemon']; // length = 3
remove_array_value(example_arr, 'banana');
banana is deleted and array length = 2
Currently there are two ways to do this
using splice()
arrayObject.splice(index, 1);
using delete
delete arrayObject[index];
But I always suggest to use splice for array objects and delete for object attributes because delete does not update array length.
If you have small array you can use filter:
myArray = ['a', 'b', 'c', 'd'];
myArray = myArray.filter(x => x !== 'b');
I have two methods.
Simple one:
arr = arr.splice(index,1)
Second one:
arr = arr.filter((v,i)=>i!==index)
The advantage to the second one is you can remove a value (all, not just first instance like most)
arr = arr.filter((v,i)=>v!==value)
OK, imagine we have this array below:
const arr = [1, 2, 3, 4, 5];
Let's do delete first:
delete arr[1];
and this is the result:
[1, empty, 3, 4, 5];
empty! and let's get it:
arr[1]; //undefined
So means just the value deleted and it's undefined now, so length is the same, also it will return true...
Let's reset our array and do it with splice this time:
arr.splice(1, 1);
and this is the result this time:
[1, 3, 4, 5];
As you see the array length changed and arr[1] is 3 now...
Also this will return the deleted item in an Array which is [3] in this case...
Easiest way is probably
var myArray = ['a', 'b', 'c', 'd'];
delete myArray[1]; // ['a', undefined, 'c', 'd']. Then use lodash compact method to remove false, null, 0, "", undefined and NaN
myArray = _.compact(myArray); ['a', 'c', 'd'];
Hope this helps.
Reference: https://lodash.com/docs#compact
For those who wants to use Lodash can use:
myArray = _.without(myArray, itemToRemove)
Or as I use in Angular2
import { without } from 'lodash';
...
myArray = without(myArray, itemToRemove);
...
delete: delete will delete the object property, but will not reindex
the array or update its length. This makes it appears as if it is
undefined:
splice: actually removes the element, reindexes the array, and changes
its length.
Delete element from last
arrName.pop();
Delete element from first
arrName.shift();
Delete from middle
arrName.splice(starting index,number of element you wnt to delete);
Ex: arrName.splice(1,1);
Delete one element from last
arrName.splice(-1);
Delete by using array index number
delete arrName[1];
If the desired element to delete is in the middle (say we want to delete 'c', which its index is 1), you can use:
var arr = ['a','b','c'];
var indexToDelete = 1;
var newArray = arr.slice(0,indexToDelete).combine(arr.slice(indexToDelete+1, arr.length))
IndexOf accepts also a reference type. Suppose the following scenario:
var arr = [{item: 1}, {item: 2}, {item: 3}];
var found = find(2, 3); //pseudo code: will return [{item: 2}, {item:3}]
var l = found.length;
while(l--) {
var index = arr.indexOf(found[l])
arr.splice(index, 1);
}
console.log(arr.length); //1
Differently:
var item2 = findUnique(2); //will return {item: 2}
var l = arr.length;
var found = false;
while(!found && l--) {
found = arr[l] === item2;
}
console.log(l, arr[l]);// l is index, arr[l] is the item you look for
Keep it simple :-
When you delete any element in an array, it will delete the value of the position mentioned and makes it empty/undefined but the position exist in the array.
var arr = [1, 2, 3 , 4, 5];
function del() {
delete arr[3];
console.log(arr);
}
del(arr);
where as in splice prototype the arguments are as follows. //arr.splice(position to start the delete , no. of items to delete)
var arr = [1, 2, 3 , 4, 5];
function spl() {
arr.splice(0, 2);
// arr.splice(position to start the delete , no. of items to delete)
console.log(arr);
}
spl(arr);
function deleteFromArray(array, indexToDelete){
var remain = new Array();
for(var i in array){
if(array[i] == indexToDelete){
continue;
}
remain.push(array[i]);
}
return remain;
}
myArray = ['a', 'b', 'c', 'd'];
deleteFromArray(myArray , 0);
// result : myArray = ['b', 'c', 'd'];

TwilioQuest Javascript Lab Constant Vigilance

OBJECTIVE:
This function should take a single argument - an array of strings. Your scan function must loop through all the strings in this array, and examine each one using boolean logic.
If a string in the input array is equal to the value contraband, add the index of that item to an output array. When you have finished scanning the entire input array, return the output array, which should contain all the indexes of suspicious items in the array.
For example, given an input array of:
['contraband', 'apples', 'cats', 'contraband', 'contraband']
Your function should return the array:
[0, 3, 4]
This list contains the position inside the input array of all the contraband strings.
MY CODE:
function scan(freightItems) {
let contrabandIndexes = [];
freightItems.forEach(el => {
console.log(freightItems.indexOf(el, 0));
if (el == "contraband") {
contrabandIndexes.push(freightItems.indexOf(el, 0));
}
});
return contrabandIndexes;
}
const indexes = scan(['dog', 'contraband', 'cat', 'zippers', 'contraband']);
console.log('Contraband Indexes: ' + indexes); // should be [1, 4]
I cant figure out why the index of the second 'contraband' is coming back as 1 and why I'm not getting past this level in TwilioQuest. Any help is appreciated.
Try something like this:
function scan(freightItems) {
let contrabandIndexes = [];
freightItems.forEach((el, idx) => {
if (el == 'contraband') {
contrabandIndexes.push(idx);
}
});
return contrabandIndexes;
}
const indexes = scan(['dog', 'contraband', 'cat', 'zippers', 'contraband']);
console.log('Contraband Indexes: ' + indexes); // should be [1, 4]
indexOf is for searching an array:
The indexOf() method returns the first index at which a given element
can be found in the array
but el is an item in the array.

How do I delete the object? [duplicate]

This question already has answers here:
Remove Object from Array using JavaScript
(32 answers)
Closed 5 years ago.
Why is there an undefined in the array? How do I delete the object?
arr = [
{id:1,name:'aaa'},
{id:2,name:'bbb'},
{id:3,name:'ccc'}
];
for(var item in arr){
if(arr.hasOwnProperty(item)){
if(arr[item].id === 2){
delete(arr[item]);
continue;
}
}
}
console.log(arr);
Hope this is what you are trying to do:-
var arr = [
{id:1,name:'aaa'},
{id:2,name:'bbb'},
{id:3,name:'ccc'}
];
arr = arr.filter(function(item){
return item.id != 2;
});
console.log(arr)
Because delete don't arranges the indexes. From the documentation
When you delete an array element, the array length is not affected.
This holds even if you delete the last element of the array
For removing you need to use Array#splice function, which removes by index. Find first the index using Array#findIndex and then pass to the splice function.
arr = [
{id:1,name:'aaa'},
{id:2,name:'bbb'},
{id:3,name:'ccc'}
];
const index = arr.findIndex(item => item.id === 2);
arr.splice(index, 1);
console.log(arr);
You need to modify the arr which is array of objects.The delete operator removes a given property from an object, in your case you need to shift the elements after removing the object
var arr = [{
id: 1,
name: 'aaa'
},
{
id: 2,
name: 'bbb'
},
{
id: 3,
name: 'ccc'
}
];
// iterating the object
arr.forEach(function(item, index) {
//checking if id === 2, if it is 2 using splice
//method to remove element from that index, & shift by one element
if (item.id === 2) {
arr.splice(index, 1)
}
})
console.log(arr);

Remove elements from array except particular one

I have two arrays. First one is an array of indexes and second one is an array of objects. They look like this:
var nums = [0, 2];
var obj = [Object_1, Object_2, Object_3];
In this particular case I need to remove all "obj" elements except obj[0] and obj[2]. So the result will look like this:
obj = [Object_2]
There are also may be cases when nums = [0, 1, 2] and obj = [Object_1, Object_2, Object_3]; In that case I dont need to remove any elements.
The "obj" length is always greater than "nums" length.
So I started with finding only the elements that I need to save:
nums.forEach(function(key) {
obj.forEach(function(o, o_key) {
if (key === o_key) {
console.log(key, o);
// deleting remaining elements
}
});
});
The question: How can I remove elements that dont meets my condition? I dont need the new array, I want to modify the existing "obj" array. How can I achieve this functionality? Or should I use some another techniques?
You coudld check if the length of the indices is the same length of the object array and return or delete the objects at the given indices.
It needs a sorted array for indices, because Array#splice changes the length of the array. (With an array with descending sorted indices, you could use Array#forEach instead of Array#reduceRight.)
function mutate(objects, indices) {
if (objects.length === indices.length) {
return;
}
indices.reduceRight(function (_, i) {
objects.splice(i, 1);
}, null);
}
var objects = [{ o: 1 }, { o: 2 }, { o: 3 }];
mutate(objects, [0, 1, 2]); // keep all items
console.log(objects);
objects = [{ o: 1 }, { o: 2 }, { o: 3 }]; // delete items at index 0 and 2
mutate(objects, [0, 2]);
console.log(objects);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can do this with a filter, assuming nums is an array on indexes of elements you want to keep.
obj = obj.filter((o, i) => nums.indexOf(i) > -1);
If you want to keep the same array object, you need to use splice e.g. in a simple reverse for in order to not mess the indices:
for (var i=obj.length-1; i>=0; i--) {
if (nums.indexOf(i) < 0) {
obj.splice(i, 1);
}
}
This is assuming the list of indices (nums) is ordered. If not, we first need to sort it:
var sortedNums = nums.sort(function (a, b) { return a - b; });
And then use the sortedNums to check the indexOf

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

I am looking for a JavaScript array insert method, in the style of:
arr.insert(index, item)
Preferably in jQuery, but any JavaScript implementation will do at this point.
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
You can implement the Array.insert method by doing this:
Array.prototype.insert = function ( index, ...items ) {
this.splice( index, 0, ...items );
};
Then you can use it like:
var arr = [ 'A', 'B', 'E' ];
arr.insert(2, 'C', 'D');
// => arr == [ 'A', 'B', 'C', 'D', 'E' ]
Other than splice, you can use this approach which will not mutate the original array, but it will create a new array with the added item. It is useful, when you need to avoid mutation. I'm using the ES6 spread operator here.
const items = [1, 2, 3, 4, 5]
const insert = (arr, index, newItem) => [
// part of the array before the specified index
...arr.slice(0, index),
// inserted item
newItem,
// part of the array after the specified index
...arr.slice(index)
]
const result = insert(items, 1, 10)
console.log(result)
// [1, 10, 2, 3, 4, 5]
This can be used to add more than one item by tweaking the function a bit to use the rest operator for the new items, and spread that in the returned result as well:
const items = [1, 2, 3, 4, 5]
const insert = (arr, index, ...newItems) => [
// part of the array before the specified index
...arr.slice(0, index),
// inserted items
...newItems,
// part of the array after the specified index
...arr.slice(index)
]
const result = insert(items, 1, 10, 20)
console.log(result)
// [1, 10, 20, 2, 3, 4, 5]
Custom array insert methods
1. With multiple arguments and chaining support
/* Syntax:
array.insert(index, value1, value2, ..., valueN) */
Array.prototype.insert = function(index) {
this.splice.apply(this, [index, 0].concat(
Array.prototype.slice.call(arguments, 1)));
return this;
};
It can insert multiple elements (as native splice does) and supports chaining:
["a", "b", "c", "d"].insert(2, "X", "Y", "Z").slice(1, 6);
// ["b", "X", "Y", "Z", "c"]
2. With array-type arguments merging and chaining support
/* Syntax:
array.insert(index, value1, value2, ..., valueN) */
Array.prototype.insert = function(index) {
index = Math.min(index, this.length);
arguments.length > 1
&& this.splice.apply(this, [index, 0].concat([].pop.call(arguments)))
&& this.insert.apply(this, arguments);
return this;
};
It can merge arrays from the arguments with the given array and also supports chaining:
["a", "b", "c", "d"].insert(2, "V", ["W", "X", "Y"], "Z").join("-");
// "a-b-V-W-X-Y-Z-c-d"
DEMO: http://jsfiddle.net/UPphH/
Using Array.prototype.splice() is an easy way to achieve it
const numbers = ['one', 'two', 'four', 'five']
numbers.splice(2, 0, 'three');
console.log(numbers)
Read more about Array.prototype.splice
If you want to insert multiple elements into an array at once check out this Stack Overflow answer: A better way to splice an array into an array in javascript
Also here are some functions to illustrate both examples:
function insertAt(array, index) {
var arrayToInsert = Array.prototype.splice.apply(arguments, [2]);
return insertArrayAt(array, index, arrayToInsert);
}
function insertArrayAt(array, index, arrayToInsert) {
Array.prototype.splice.apply(array, [index, 0].concat(arrayToInsert));
return array;
}
Finally here is a jsFiddle so you can see it for yourself: http://jsfiddle.net/luisperezphd/Wc8aS/
And this is how you use the functions:
// if you want to insert specific values whether constants or variables:
insertAt(arr, 1, "x", "y", "z");
// OR if you have an array:
var arrToInsert = ["x", "y", "z"];
insertArrayAt(arr, 1, arrToInsert);
Solutions & Performance
Today (2020.04.24) I perform tests for chosen solutions for big and small arrays. I tested them on macOS v10.13.6 (High Sierra) on Chrome 81.0, Safari 13.1, and Firefox 75.0.
Conclusions
For all browsers
surprisingly for small arrays, non-in-place solutions based on slice and reduce (D,E,F) are usually 10x-100x faster than in-place solutions
for big arrays the in-place-solutions based on splice (AI, BI, and CI) was fastest (sometimes ~100x - but it depends on the array size)
for small arrays the BI solution was slowest
for big arrays the E solution was slowest
Details
Tests were divided into two groups: in-place solutions (AI, BI, and CI) and non-in-place solutions (D, E, and F) and was performed for two cases:
test for an array with 10 elements - you can run it here
test for an array with 1,000,000 elements - you can run it here
Tested code is presented in the below snippet:
jsfiddle
function AI(arr, i, el) {
arr.splice(i, 0, el);
return arr;
}
function BI(arr, i, el) {
Array.prototype.splice.apply(arr, [i, 0, el]);
return arr;
}
function CI(arr, i, el) {
Array.prototype.splice.call(arr, i, 0, el);
return arr;
}
function D(arr, i, el) {
return arr.slice(0, i).concat(el, arr.slice(i));
}
function E(arr, i, el) {
return [...arr.slice(0, i), el, ...arr.slice(i)]
}
function F(arr, i, el) {
return arr.reduce((s, a, j)=> (j-i ? s.push(a) : s.push(el, a), s), []);
}
// -------------
// TEST
// -------------
let arr = ["a", "b", "c", "d", "e", "f"];
let log = (n, f) => {
let a = f([...arr], 3, "NEW");
console.log(`${n}: [${a}]`);
};
log('AI', AI);
log('BI', BI);
log('CI', CI);
log('D', D);
log('E', E);
log('F', F);
This snippet only presents tested code (it not perform tests)
Example results for a small array on Google Chrome are below:
For proper functional programming and chaining purposes, an invention of Array.prototype.insert() is essential. Actually, the splice could have been perfect if it had returned the mutated array instead of a totally meaningless empty array. So here it goes:
Array.prototype.insert = function(i,...rest){
this.splice(i,0,...rest)
return this
}
var a = [3,4,8,9];
document.write("<pre>" + JSON.stringify(a.insert(2,5,6,7)) + "</pre>");
Well, OK, the above with the Array.prototype.splice() one mutates the original array and some might complain like "you shouldn't modify what doesn't belong to you" and that might turn out to be right as well. So for the public welfare, I would like to give another Array.prototype.insert() which doesn't mutate the original array. Here it goes;
Array.prototype.insert = function(i,...rest){
return this.slice(0,i).concat(rest,this.slice(i));
}
var a = [3,4,8,9],
b = a.insert(2,5,6,7);
console.log(JSON.stringify(a));
console.log(JSON.stringify(b));
You can use splice() for this
The splice() method usually receives three arguments when adding an element:
The index of the array where the item is going to be added.
The number of items to be removed, which in this case is 0.
The element to add.
let array = ['item 1', 'item 2', 'item 3']
let insertAtIndex = 0
let itemsToRemove = 0
array.splice(insertAtIndex, itemsToRemove, 'insert this string on index 0')
console.log(array)
I recommend using pure JavaScript in this case. Also there isn't any insert method in JavaScript, but we have a method which is a built-in Array method which does the job for you. It's called splice...
Let's see what's splice()...
The splice() method changes the contents of an array by removing
existing elements and/or adding new elements.
OK, imagine we have this array below:
const arr = [1, 2, 3, 4, 5];
We can remove 3 like this:
arr.splice(arr.indexOf(3), 1);
It will return 3, but if we check the arr now, we have:
[1, 2, 4, 5]
So far, so good, but how we can add a new element to array using splice?
Let's put back 3 in the arr...
arr.splice(2, 0, 3);
Let's see what we have done...
We use splice again, but this time for the second argument, we pass 0, meaning we don't want to delete any item, but at the same time, we add a third argument which is the 3 that will be added at second index...
You should be aware that we can delete and add at the same time. For example, now we can do:
arr.splice(2, 2, 3);
Which will delete two items at index 2. Then add 3 at index 2 and the result will be:
[1, 2, 3, 5];
This is showing how each item in splice work:
array.splice(start, deleteCount, item1, item2, item3 ...)
Here are two ways:
const array = [ 'My', 'name', 'Hamza' ];
array.splice(2, 0, 'is');
console.log("Method 1: ", array.join(" "));
Or
Array.prototype.insert = function ( index, item ) {
this.splice( index, 0, item );
};
const array = [ 'My', 'name', 'Hamza' ];
array.insert(2, 'is');
console.log("Method 2 : ", array.join(" "));
Append a single element at a specific index
// Append at a specific position (here at index 1)
arrName.splice(1, 0,'newName1');
// 1: index number, 0: number of element to remove, newName1: new element
// Append at a specific position (here at index 3)
arrName[3] = 'newName1';
Append multiple elements at a specific index
// Append from index number 1
arrName.splice(1, 0, 'newElemenet1', 'newElemenet2', 'newElemenet3');
// 1: index number from where append start,
// 0: number of element to remove,
//newElemenet1,2,3: new elements
Array#splice() is the way to go, unless you really want to avoid mutating the array. Given 2 arrays arr1 and arr2, here's how you would insert the contents of arr2 into arr1 after the first element:
const arr1 = ['a', 'd', 'e'];
const arr2 = ['b', 'c'];
arr1.splice(1, 0, ...arr2); // arr1 now contains ['a', 'b', 'c', 'd', 'e']
console.log(arr1)
If you are concerned about mutating the array (for example, if using Immutable.js), you can instead use slice(), not to be confused with splice() with a 'p'.
const arr3 = [...arr1.slice(0, 1), ...arr2, ...arr1.slice(1)];
Another possible solution, with usage of Array.reduce.
const arr = ["apple", "orange", "raspberry"];
const arr2 = [1, 2, 4];
const insert = (arr, item, index) =>
arr.reduce(function(s, a, i) {
i === index ? s.push(item, a) : s.push(a);
return s;
}, []);
console.log(insert(arr, "banana", 1));
console.log(insert(arr2, 3, 2))
Even though this has been answered already, I'm adding this note for an alternative approach.
I wanted to place a known number of items into an array, into specific positions, as they come off of an "associative array" (i.e. an object) which by definition is not guaranteed to be in a sorted order. I wanted the resulting array to be an array of objects, but the objects to be in a specific order in the array since an array guarantees their order. So I did this.
First the source object, a JSONB string retrieved from PostgreSQL. I wanted to have it sorted by the "order" property in each child object.
var jsonb_str = '{"one": {"abbr": "", "order": 3}, "two": {"abbr": "", "order": 4}, "three": {"abbr": "", "order": 5}, "initialize": {"abbr": "init", "order": 1}, "start": {"abbr": "", "order": 2}}';
var jsonb_obj = JSON.parse(jsonb_str);
Since the number of nodes in the object is known, I first create an array with the specified length:
var obj_length = Object.keys(jsonb_obj).length;
var sorted_array = new Array(obj_length);
And then iterate the object, placing the newly created temporary objects into the desired locations in the array without really any "sorting" taking place.
for (var key of Object.keys(jsonb_obj)) {
var tobj = {};
tobj[key] = jsonb_obj[key].abbr;
var position = jsonb_obj[key].order - 1;
sorted_array[position] = tobj;
}
console.dir(sorted_array);
Immutable insertion
Using the splice method is surely the best answer if you need to insert into an array in-place.
However, if you are looking for an immutable function that returns a new updated array instead of mutating the original array on insert, you can use the following function.
function insert(array, index) {
const items = Array.prototype.slice.call(arguments, 2);
return [].concat(array.slice(0, index), items, array.slice(index));
}
const list = ['one', 'two', 'three'];
const list1 = insert(list, 0, 'zero'); // Insert single item
const list2 = insert(list, 3, 'four', 'five', 'six'); // Insert multiple
console.log('Original list: ', list);
console.log('Inserted list1: ', list1);
console.log('Inserted list2: ', list2);
Note: This is a pre-ES6 way of doing it, so it works for both older and newer browsers.
If you're using ES6 then you can try out rest parameters too; see this answer.
Anyone who's still having issues with this one and have tried all the options in previous answers and never got it. I'm sharing my solution, and this is to take into consideration that you don't want to explicitly state the properties of your object vs the array.
function isIdentical(left, right){
return JSON.stringify(left) === JSON.stringify(right);
}
function contains(array, obj){
let count = 0;
array.map((cur) => {
if(this.isIdentical(cur, obj))
count++;
});
return count > 0;
}
This is a combination of iterating the reference array and comparing it to the object you wanted to check, converting both of them into a string, and then iterating if it matched. Then you can just count. This can be improved, but this is where I settled.
Taking profit of the reduce method as follows:
function insert(arr, val, index) {
return index >= arr.length
? arr.concat(val)
: arr.reduce((prev, x, i) => prev.concat(i === index ? [val, x] : x), []);
}
So in this way we can return a new array (will be a cool functional way - more much better than using push or splice) with the element inserted at index, and if the index is greater than the length of the array it will be inserted at the end.
I tried this and it is working fine!
var initialArr = ["India","China","Japan","USA"];
initialArr.splice(index, 0, item);
Index is the position where you want to insert or delete the element.
0, i.e., the second parameter, defines the number of elements from the index to be removed.
item contains the new entries which you want to make in the array. It can be one or more than one.
initialArr.splice(2, 0, "Nigeria");
initialArr.splice(2, 0, "Australia","UK");
I have to agree with Redu's answer because splice() definitely has a bit of a confusing interface. And the response given by cdbajorin that "it only returns an empty array when the second parameter is 0. If it's greater than 0, it returns the items removed from the array" is, while accurate, proving the point.
The function's intent is to splice or as said earlier by Jakob Keller, "to join or connect, also to change.
You have an established array that you are now changing which would involve adding or removing elements...." Given that, the return value of the elements, if any, that were removed is awkward at best. And I 100% agree that this method could have been better suited to chaining if it had returned what seems natural, a new array with the spliced elements added. Then you could do things like ["19", "17"].splice(1,0,"18").join("...") or whatever you like with the returned array.
The fact that it returns what was removed is just kind of nonsense IMHO. If the intention of the method was to "cut out a set of elements" and that was its only intent, maybe. It seems like if I don't know what I'm cutting out already though, I probably have little reason to cut those elements out, doesn't it?
It would be better if it behaved like concat(), map(), reduce(), slice(), etc. where a new array is made from the existing array rather than mutating the existing array. Those are all chainable, and that is a significant issue. It's rather common to chain array manipulation.
It seems like the language needs to go one or the other direction and try to stick to it as much as possible. JavaScript being functional and less declarative, it just seems like a strange deviation from the norm.
I like a little safety and I use this:
Array.prototype.Insert = function (item, before) {
if (!item) return;
if (before == null || before < 0 || before > this.length - 1) {
this.push(item);
return;
}
this.splice(before, 0, item);
}
var t = ["a", "b"]
t.Insert("v", 1)
console.log(t)
You can do it with array.splice:
/**
* #param arr: Array
* #param item: item to insert
* #param index: index at which to insert
* #returns array with the inserted element
*/
export function _arrayInsertAt<T>(arr: T[], item: T, index: number) {
return arr.splice(index, 0, item);;
}
Doc of array.slice
Here's a working function that I use in one of my applications.
This checks if an item exists:
let ifExist = (item, strings = [ '' ], position = 0) => {
// Output into an array with an empty string. Important just in case their isn't any item.
let output = [ '' ];
// Check to see if the item that will be positioned exist.
if (item) {
// Output should be equal to an array of strings.
output = strings;
// Use splice() in order to break the array.
// Use positional parameters to state where to put the item
// and 0 is to not replace an index. Item is the actual item we are placing at the prescribed position.
output.splice(position, 0, item);
}
// Empty string is so we do not concatenate with comma or anything else.
return output.join("");
};
And then I call it below.
ifExist("friends", [ ' ( ', ' )' ], 1)} // Output: ( friends )
ifExist("friends", [ ' - '], 1)} // Output: - friends
ifExist("friends", [ ':'], 0)} // Output: friends:
Here is the modern (Typescript functional) way:
export const insertItemInList = <T>(
arr: T[],
index: number,
newItem: T
): T[] => [...arr.slice(0, index), newItem, ...arr.slice(index)]
I do it like so:
const insert = (what, where, index) =>
([...where.slice(0, index), what , ...where.slice(index, where.length)]);
const insert = (what, where, index) =>
([...where.slice(0, index), what , ...where.slice(index, where.length)]);
const list = [1, 2, 3, 4, 5, 6];
const newList = insert('a', list, 2);
console.log(newList.indexOf('a') === 2);
Here's a simple function that supports inserting multiple values at the same time:
function add_items_to_array_at_position(array, index, new_items)
{
return [...array.slice(0, index), ...new_items, ...array.slice(index)];
}
Usage example:
let old_array = [1,2,5];
let new_array = add_items_to_array_at_position(old_array, 2, [3,4]);
console.log(new_array);
//Output: [1,2,3,4,5]
var array= [10,20,30,40]
var i;
var pos=2; //pos=index + 1
/*pos is position which we want to insert at which is index + 1.position two in an array is index 1.*/
var value=5
//value to insert
//Initialize from last array element
for(i=array.length-1;i>=pos-1;i--){
array[i+1]=array[i]
}
array[pos-1]=value
console.log(array)
Multi purpose for ARRAY and ARRAY OF OBJECT reusable approach
let arr = [0,1,2];
let obj = [{ name: "abc"},{ name: "xyz"},{ name: "ijk"} ];
const addArrayItemAtIndex = ( array, index, newItem ) => {
return [...array.slice(0, index), newItem, ...array.slice(index)];
}
// For Array
console.log( addArrayItemAtIndex(arr, 2, 159 ) );
// For Array of Objects
console.log( addArrayItemAtIndex(obj, 0, { name: "AMOOS"} ) );

Categories