VueJS pushing to an array also pushes the value to another one - javascript

Has any vuejs veteran experience this on VueJS(v2) where you have 2 arrays on a Component, and you push a value to the 1st array and the 2nd array gets the value also WITHOUT TOUCHING IT.
This is the first time I've encountered this, fyi I've been using VueJS for more than 2yrs already.
Additional information I have a VERY VERY similar component with exactly the same data variables and it doesn't happen, only on the 2nd Component.
array1 = [];
array2 = [];
array1.push('gether');
output should be
array1 = ['gether'];
array2 = [];
WHAT ACTUALLY HAPPENS
array1 = ['gether'];
array2 = ['gether'];
I've also played with the Google DevTools Vue Debugger.
Adding an entry on the array1 ONLY also adds the value on the array2.
kinda mind boggling

Because arrays in JS are reference values, so when you try to copy it using the = it will only copy the reference to the original array and not the value of the array. To create a real copy of an array, you need to copy over the value of the array under a new value variable. That way this new array does not reference to the old array address in memory.
To achieve this you can use array.slice() method as it creates a new array not a mere reference !
See Example and understand difference =>
Using reference (=)
let array = ["some text"]
// Making it equal to main array and using reference to copy
array1 = array;
array2 = array;
array1.push('gether');
console.log(array2)
Using array.slice() to clone
let array = ["some text"]
// Making it equal to main array and using slice to copy
array1 = array.slice();
array2 = array.slice();
array1.push('gether');
console.log(array2)

When you make two arrays equal to the same value, you make them equal by reference.
So
foo = ['a', 'b', 'z']
array1 = foo;
array2 = foo;
array1.push('d');
console.log(array2) //Outputs: ['a', 'b', 'c', 'd']
Is expected behaviour.
However that is not the same as the given example in your question. Run snippet below to see the difference.
To avoid this, you can use slice() to create a copy of the original array. I added an example to the code snippet.
let foo = ["a", "b"];
let array1 = foo;
let array2 = foo;
array2.push("c");
console.log(foo); // Outputs ["a", "b", "c"]
console.log(array1); // Outputs ["a", "b", "c"]
let array3 = [];
let array4 = [];
array4.push("a");
console.log(array3); // Outputs []
console.log(array4); // Outputs ["a"]
let bar = ["a", "b"];
let array5 = bar.slice();
bar.push("c");
console.log(bar); // Outputs ["a", "b", "c"]
console.log(array5); // Outputs ["a", "b"]

Related

create two differents variables from the same array [duplicate]

This question already has answers here:
Copy array by value
(39 answers)
Closed 3 years ago.
I've an array, and I want to create 2 differents variables from the same array but this variables must have different result. For example, an array of string : the first variable must contain this array, and the other variable must contains this values but sorted. But it's not working :
var letters = ['b', 'c', 'a']; // datas
const lettersUnsorted = letters; // i want the array like the var "letters"
const letterSorted = letters.sort(); // i want the array like the var "letters" but sorted
console.log(letterSorted); // OK => returns: ["a", "b", "c"]
console.log(lettersUnsorted); // KO => returns: ["a", "b", "c"] instead of ['b', 'c', 'a']
You should make a copy the array first because sort() method modifies the original array. You can make the copy of the array using slice()
var letters = ['b', 'c', 'a'];
const lettersUnsorted = letters;
const letterSorted = letters.slice().sort(); //this line is changed
console.log(letterSorted);
console.log(lettersUnsorted);
This is because the reference to the original letters array is maintained.
lettersUnsorted and letterSorted are both referencing to the letters variable. This is because letters is an array (which is technically an object), and in JavaScript, assigning another variable to it will result in assignment by reference (rather than assignment by value). Therefore, any operations or mutation to letters will result in both lettersUnsorted and letterSorted in having the same result as letters, due to the reference to letter.
You should create a shallow clone of the original letters array. This will allow you to safely carry out any mutation without affecting the other array. We can achieve this using ES6's spread syntax.
const letters = ['b', 'c', 'a'];
const lettersClone = [...letters].sort();
console.log(letters);
console.log(lettersClone);
you can use concat also.
var letters = ['b', 'c', 'a'];
const lettersUnsorted = letters;
const letterssorted = ([].concat(letters)).sort();

Unwanted double assignment on array function

function myFunction()
{
var Arr2
if(Arr1!=null)
{
Arr2=Arr1
console.log("Arr2 before for: "+Arr2)
console.log("Arr1 before for: "+Arr1)
}
for(var index=-1+Arr2.length;index>=0;index--)
{
if(Arr2[index]=="to_delete")
{
Arr2.splice(index,1)
}
}
console.log("Arr1 after for: "+Arr1)
console.log("Arr2 after for: "+Arr2)
}
I create Arr2 in a function, Arr2=Arr1, the problem is that Arr1 is also being spliced during for, and from these last two console.logs i am informed that these 2 arrays are the same. (I only want to change Arr2)
When you do Arr2 = Arr1, you're just copying the reference to that array, you're not making a copy of the array itself. So both Arr1 and Arr2 will now refer to the same array.
Try changing
Arr2=Arr1
to
Arr2 = Arr1.slice()
which should copy all of the elements in Arr1 to the new Arr2. Check out Array.prototype.slice for more info.
You could just use filter Array method like this :
var arr2 = arr1.filter(x => x!="to_delete");
You are creating a reference to Arr1, not a new object.
Think of it this way:
Think of it this way: when you initialise Arr1, you're allocating it to a piece of memory on the heap. This reference is then given an address.
The assignment var Arr2 = Arr1 equals the same as saying, Arr2 is the same as Arr1 by reference. Which means it points to the same memory address.
If you want to make a copy of an object, a.k.a. pass it by value, you should use one of the following methods.
var Arr2 = Arr1.slice(0);
Keep in mind however that if your array contains objects, these are cloned by reference with this method. Example:
var Arr1 = [{a: 1, b: 2, c:3}, {d: 4, e: 5, f: 6}]
var Arr2 = Arr1.slice(0)
Arr1[0].a = 2;
console.log(Arr2[0].a) // this will output 2
If you want to easily do a deep clone without having to write the code to pass the object references by value, you can use something like lodash or just:
var Arr2 = JSON.parse(JSON.stringify(Arr1));
Which also works.

Merge two arrays by grouping based on elements of 1st array in Javascript

I have two arrays (arr1 & arr2) like this
var arr1 = ["A","B","C"];
var arr2 = [["A","aa"], ["A","ab"], ["A","ac"],["B","ba"],["B","bb"],["B","bc"],["C","ca"],["C","cb"]];
I want to group them together into 3rd array in javascript based on the values of first array. Desired Output:
arr3 = [ ["A",["aa","ab","ac"]], ["B",["ba","bb","bc"] ], ["C",["ca","cb"]] ]
NOTE: I had arr2 to begin with and was able to retrieve first value and remove duplicates into arr1.
Please advise.
Try like this
var arr1 = ["A", "B", "C"];
var arr2 = [
["A", "aa"],
["A", "ab"],
["A", "ac"],
["B", "ba"],
["B", "bb"],
["B", "bc"],
["C", "ca"],
["C", "cb"]
];
var newVal = arr1.map(function(x) {
var filter = arr2.filter(function(y) {
return y[0] == x;
}).map(function(y) {
return y[1];
});
return [x, filter];
})
console.log(newVal);
DEMO
NOTE: I had arr2 to begin with and was able to retrieve first value and remove duplicates into arr1.
Rather than creating arr1 as a middle step, I would probably create an object as the middle step:
var obj = arr2.reduce(function(a,b){
if (!a[b[0]]) a[b[0]] = [];
a[b[0]].push(b[1]);
return a;
},{});
// obj is now {"A":["aa","ab","ac"],"B":["ba","bb","bc"],"C":["ca","cb"]}
To convert that object to your desired output array:
var arr3 = Object.keys(obj).map(function(v) { return [v, obj[v]]; });
// [["A",["aa","ab","ac"]],["B",["ba","bb","bc"]],["C",["ca","cb"]]]
If you actually need the arr1 array for something else then:
var arr1 = Object.keys(obj);
// ["A", "B", "C"]
But notice that obj is quite useful for further processing, because if you need to get the values associated with "B" you don't need to search through an array again, you can simply say obj["B"] (which will give the array ["ba","bb","bc"]). So the second "B" value is obj["B"][1].
Further reading:
.reduce()
.map()
Object.keys()

How to use array variable in array?

I have an array and I want to put same array and other array inside of the first array.
var arr=["a","b","c",arr,arr2];
var arr2=["a","b"];
var arr3=[];
arr3=arr[3];
When I print out arr, I can see
["a","b","c",,]
But if I print out arr3, The result is undefined.
How can I fix it?
You need to do this in the right order:
var arr1 = [];
var arr2 = [ "a", "b" ];
// Now arr1 and arr2 are defined so you can throw them into another array:
var arr3 = [ "a", "b", "c", arr1, arr2 ];
You've defined arr as part of itself - arr[3] is arr. But at the time, arr doesn't exist yet, so it comes out as undefined.

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