How to remove item from array and save it in one command? - javascript

How to remove an element of an array and have that removed element saved in a variable:
var item = arr.remove(index)

You can use Array.prototype.splice for this purpose:
const arr = ['a', 'b', 'c'];
const removed = arr.splice(1, 1).pop();
console.log(arr) // ['a', 'c'];
console.log(removed) // 'b'
Note that in the example above, splice is chained with Array.prototype.pop - that's because splice, as mentioned by #Andreas, always returns an Array, so pop is used to extract the single value from Array returned by splice.

What you're looking for is splice. This takes as parameters the index of the item to remove, and the count of items from that to take out. Because you only want to remove 1 item, the 2nd parameter will always be 1. Splice also returns as an array, so we're indexing that [0] to get just the contents.
var arr = ['a','b','c'];
var item = arr.splice(1,1)[0]; // 'b'

Maybe something like this?
Array.prototype.remove=function(i){
var item=this[i]
this.splice(i,1)
return item
}
arr=[1,2,3]
item=arr.remove(1)
console.log(item) //2
console.log(arr) //[1,3]
I hope that this will help you!

Related

Find a unique number in an array

Can someone explain to me what exactly is this line of code doing?
function findUniq(array) {
return array.find((item) => array.indexOf(item) === array.lastIndexOf(item))
}
I want to know what this line is exactly doing:
return array.find((item) => array.indexOf(item) === array.lastIndexOf(item))
What I think is happening here is that for every item inside the array it is comparing the first index of that item to the last index of item. it returns the items that equal to eachother.
I don't understand how it is returning the unique array.
If I were to write this function it would be like this:
return array.find((item) => array.indexOf(item) != array.lastIndexOf(item))
However, that doesn't work since it is returning the common number.
thanks
The Array.prototype.find() method takes a predicate function (a function that returns true or false based on input parameters) and then returns the element provided the predicate is true.
In your case, given the scenario:
var array1 = [1,2,1,3,5,2,3];
var array2 = [1,2,1,3,5,5,3];
function findUnique(array){
return array.find(
// The code below runs for every element of the array.
// - for each element, it takes the element and checks if first position, is the same as last position in the array
(item) => array.indexOf(item) === array.lastIndexOf(item) //
);
}
console.log("For array 1, unique item is: ",findUnique(array1));
console.log("For array 2, unique item is: ",findUnique(array2));
Array.prototype.indexOf(yourArrayElement) returns the position of the first occurrence of yourArrayElement
Oh the other hand, Array.prototype.lastIndexOf(yourArrayElement) returns the position of the last occurrence of yourArrayElement
If yourArrayElement only exists once within the array, the first and last position will be the same and Array.prototype.find() will return that element.
indexOf returns the first found position of the given element in the array whereas lastIndexOf returns the latest position of the given element in the array.
If indexOf === lastIndexOf, it means the first found element is the same as the latest one --> the element is unique in the array.
The reason that it return a unique number, because the find function loop from the start and from the end on each iteration, so if the index of both indexOf that loops from the start and lastIndexOf that loops from the end is equal it's mean that there are no duplicates across the array beside the current item.
This can be written two ways:
Match the first occurrence index with the final occurrence index.
const data = ['a', 'b', 'c', 'b', 'a'];
const findUniq = arr =>
arr.find((item) => arr.indexOf(item) === arr.lastIndexOf(item));
console.log(findUniq(data)); // 'c'
Check for an index of -1 for the next indexOf check.
const data = ['a', 'b', 'c', 'b', 'a'];
const findUniq = arr =>
arr.find((item) => arr.indexOf(item, arr.indexOf(item) + 1) === -1);
console.log(findUniq(data)); // 'c'
The first one is easier to read and convey, because it it written to compare the first and last index check. The second one is more obscure, but both work.

What meaning the dash in array when iterating an array in for of loop with entries iterator?

If I normally use for of loop and use iterator as entries that situation look like this:
var a = ['a', 'b', 'c'];
var iterator = a.entries();
for (let e of iterator) {
console.log(e);
}
// [0, 'a']
// [1, 'b']
// [2, 'c']
iterator: will be the entire array that contain all elements key/value pair. Key will be the index.
e: will be an element in the array
BUT what is this??????
let text = "A A A";
let splitwords = text.split(" ");
let words = [];
for (const [, item] of splitwords.entries()) {
words.push(item.split(""));
}
console.log(`This is the words: ${words}`);
what meaning the [, item] part???
and why should i use this pattern?
text.split("") do exactly same thing or not?
(Otherwise I try solve an text animation problem and this inherit from that code:
framer motion text animation )
Thank you
PS: I know this is an array destructing my main question that why????
for (const [, item] of splitwords.entries()) {
words.push(item.split(""));
}
[, item] is called array destructing, and the reason for that is because of entries in splitwords.entries(). The result of that array is like this [0, "a"],[1, "b"] (the first item is an index, and the second item is value), but in this case, they don't use an index, so the declaration is like [,item] (If they want to use it, the code can be [index, item]).
Without using an index, they can implement this way
for (const item of splitwords) { //remove entries and array destructing
words.push(item.split(""));
}
and why should I use this pattern?
Well, I think this is just their code style to use for of for collecting both index and value together. It depends on you need an index or not.
words.push(item.split("")) is different from the above case, they try to make the entire word "Hello" into characters ["H","e","l","l","o"] for the animation, so the final result of words can be
[
["F","r","a","m","e"],
["M","o","t","i","o","n"],
...
]
It's just a way to skip destructuring the first element in the array. You are basically saying that you are not interested in the first array item.
Since the entries() method returns a new Array Iterator object that contains the key/value pairs for each index in the array.
const foo = ['a', 'b', 'c'];
for (const [, item] of foo.entries()) {
// item would be 'a', 'b', 'c'
}
for (const [index, item] of foo.entries()) {
// item would be 'a', 'b', 'c'
// index would be 0, 1, 2
}
This is a destructuring assignment.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment
Array.prototype.entries() returns an array of 2 elements for the index and the item itself for each array item.
So in this expression the index is assign to nothing (because there is no variable declared before the comma) and the item is assigned to item.
Example
const ar = [1,2]
const [,value2]=ar
console.log(value2)
const [value1,]=ar
console.log(value1)
const [v1, v2] = ar
console.log(v1, v2)
For the item.split("") it just seems useless, the result would be the same in the present case with just words.push(item) since each word is just one letter... If the words were more than one letter this would just store each letter separately in the words array. Which could maybe be called letters I guess...
Edit:
for the "why use this pattern" question. In the present case, again it just seems useless. The index is not used so calling entries just don't seems relevant.
I don't know if you 'should' use this pattern, but if you want an explanation of what it is, it's like
for(let temp of splitwords.entries()){
const [, item] = temp;
words.push(item.split('');
}
And then const [, item] = temp; is basically the same as const item = temp[1].
Due to how ".entries()" work for an array (giving [index, value]), since the index is ignored by the destructuring, the resulting item is just the value. So, I don't think the result is any different from the following:
for (const item of splitwords) {
words.push(item.split(""));
}
Maybe they were preparing for the future, in case the index becomes important some day.

Rotate the elements of an array

I am trying to solve a javascript challenge from jshero.net. The challenge is this:
Write a function rotate that rotates the elements of an array. All
elements should be moved one position to the left. The 0th element
should be placed at the end of the array. The rotated array should be
returned. rotate(['a', 'b', 'c']) should return ['b', 'c', 'a'].
All I could come up with was this :
function rotate(a){
let myPush = a.push();
let myShift = a.shift(myPush);
let myFinalS = [myPush, myShift]
return myFinalS
}
But the error message I got was:
rotate(['a', 'b', 'c']) does not return [ 'b', 'c', 'a' ], but [ 3,
'a' ]. Test-Error! Correct the error and re-run the tests!
I feel like I'm missing something really simple but I can't figure out what. Do you guys have other ways to solve this?
function rotate(array){
let firstElement = array.shift();
array.push(firstElement);
return array;
}
To achieve the output you are looking for, first you have to use Array.shift() to remove the first element, then using Array.push() add the element back to the end of the Array, then return the array, the issue is that you used the wrong oder for these steps, also .push() method takes element to be added as argument, here is a working snippet:
function rotate(a){
let myShift = a.shift();
a.push(myShift);
return a;
}
console.log(rotate(['a', 'b', 'c']));
Here I have created a utility where, the input array will not get mutated even after rotating the array as per the requirement.
function rotate(a){
let inputCopy = [...a]
let myShift = inputCopy.shift();
let myFinalS = [...inputCopy, myShift]
return myFinalS
}
console.log(rotate([1,2,3]))
console.log(rotate(["a","b","c"]))
Hope this helps.
function rotate(arr){
let toBeLast = arr[0];
arr.splice(0, 1);
arr.push(toBeLast);
return arr;
}
console.log(rotate(['a', 'b', 'c']));
New to stack overflow. Hope this helps :)
arr.unshift(...arr.splice(arr.indexOf(k)))
Using unshift(), splice() and indexOf(), this is a one line that should help. arr is the array you want to rotate and k the item you want as first element of the array. An example of function could be:
let rotate = function(k, arr) {
arr.unshift(...arr.splice(arr.indexOf(k)))
}
And this are examples of usage:
let array = ['a', 'b', 'c', 'd']
let item = 'c'
rotate(item, array)
console.log(array)
// > Array ["c", "d", "a", "b"]
Finally back to the original array:
rotate('a', array)
console.log(array)
// > Array ["a", "b", "c", "d"]

What's an easy way of storing an array of numbers in Javascript that I can add/remove from?

In C# I would create a List then I could add and remove numbers very easily. Does identical functionality exist in Javascript, or do I have to write my own methods to search and remove items using a loop?
var NumberList = [];
NumberList.Add(17);
NumberList.Add(25);
NumberList.Remove(17);
etc.
I know I can use .push to add a number, so I guess it's really how to remove an individual number without using a loop that I'm looking for.
edit: of course, if there's no other way then I'll use a loop!:)
The Array objet has this kind of method :
var myArray = new Array();
myArray.push(12);
myArray.push(10);
myArray.pop();
All detail can be found here
To remove a specific value , some tricks are possible :
var id = myArray.indexOf(10); // Find the index
if(id!=-1) myArray.splice(id, 1);
You have to use splice and indexOf if you know that there is only one copy of the value that you want to remove and if there can be many copies then you have to use splice in a loop.
If you're using Underscore.js then you can use:
array = _.without(array, 17);
To remove array element by value :
Array.prototype.removeByValue = function(val) {
for(var i=0; i<this.length; i++) {
if(this[i] == val) {
this.splice(i, 1);
break;
}
}
}
var myarray = ["one", "two", "three", "four", "five"];
myarray.removeByValue("three");
console.log(myarray); // ["one", "two", "four", "five"];
or in your case an array of numbers:
var myarray = [1, 2, 3, 4, 5];
myarray.removeByValue(3);
console.log(myarray); // [1, 2, 4, 5];
to remove by index you'll have to use splice():
myarray.splice(2,1); //position at 2nd element and remove 1 element
console.log(myarray); // ["one", "two", "four", "five"];
var NumberList = {};
NumberList[17] = true;
NumberList[25] = true;
delete NumberList[17];
This uses the "associative array"-characteristic of JavaScript objects to let you store and retrieve values by index in an object.
I used true as the value, but you can use anything you like, as it is not important (at least as per your example). You could of course store more useful things there. Using true has the nice side-effect that you can do an existence-check like this:
if (NumberList[25]) // evaluates to "true"
if (NumberList[26]) // evaluates to "undefined" (equivalent to "false" here)
The same would work with actual array objects, by the way.
var NumberList = [];
NumberList[17] = true;
NumberList[25] = true;
delete NumberList[17];
but these would not be "sparse" - NumberList[25] = true creates an 26-element array with all preceding array elements set to undefined.
Using objects instead is sparse, no additional members are created.
If you want in-place removal, then indexOf and splice can be used together. To remove all occurrences of 17, use
var index;
while((index = NumberList.indexOf(17)) != -1) {
NumberList.splice(index, 1);
}
If you don't care about in-place removals, then the filter method can be used.
NumberList = NumberList.filter(function(number) {
return number != 17;
});
You could store the index of each added element (number). And then use splice to remove by index. John has a good array remove function to remove by index.
Something like:
var array = [];
var number = { val: 10, index: null };
// add to array
array.push(number.val);
number.index = array.length - 1;
// remove (using John's remove function)
array.remove(number.index);
// remove using splice
array.splice(number.index, 1);
I've solved it by using the JQuery function inArray(); combined with splice().
indexOf and inArray seem to be identical, however indexOf isn't supported in IE6 or 7 as it turns out, so I had to either write my own or use JQuery, and I use JQuery anyway.

Deleting array elements in JavaScript - delete vs splice

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'];

Categories

Resources