delete array[x] deleting value but not the whole element - javascript

I have an object which has duplicate values so i used delete new_object[1] to delete the value but when I see this in console its showing undefined in object 0800
["293", undefined, "298", "297"]

You should use
arr.splice(index, 1);
delete only removes the element, but keeps the indexes. This question is similar in nature and provides more information.

I think you should use splice
a = ["1","2","3"];
a.splice(1,0)
console.log(a) //["1","3"]

var test = [1,2,3,4];
delete test[1];
now if you print the test variable, you will get
=> [ 1, , 3, 4 ]
that is why you have got undefined
like everyone here is answering, you should use splice
test.splice(1,1);
and now print the test variable will give you
=> [ 1, 3, 4, 5 ]

you need to use splice() in order to remove the value from the array. What you are doing is simply setting it to undefined.
var myArray = ['295', '296', '297', '298'];
// removes 1 element from index 2
var removed = myArray.splice(2, 1);
// myArray is ['295', '296', '298'];
// removed is ['297']
Reference from Array.splice
The splice() method changes the content of an array by removing
existing elements and/or adding new elements.

Related

JS Splice Array of Nulls Removes Last Index Regardless of Parameters

For a reason specific to this application an array of data or nulls is used to display a list of forms. The difference is based on whether data was provided by a service or manually added, where null indicates everything was manually added via
a button not a service.
So ignoring the use case of an array of nulls it turns out that [null, null, null].splice(0, 1); removes the null at index 2 instead of 0 based on entering values into the different forms displayed based on the array length, and then seeing who disappears on delete.
It can be made to work by adding something unique like { index: theIndex } to the array instead of null. So splice now works correctly removing the item at index 0 instead of 2, but now I'm curious what splice does under the covers that it can't remove an index regardless of its value compared to the other indices.
Can anyone explain what splice is doing? Based on the spec for splice I don't really see why this happens.
(This follows from the comments in the question but is too large to be a comment).
So I think you are having a conceptual misconception (^^). Look at this examples:
let a = [1, 2, 3]
a.splice(0, 1) // => 1
a // => [2, 3]
let b = [1, 2, 3]
delete b[0] // => true
b // => [<1 empty slot>, 2, 3]
The splice function modifies the array in-place. Note that, although we spliced the first element, we got as a result an array of two elements.
Look now at this example
let a = [1, 1, 1]
a.splice(0, 1)
a // => [1, 1]
let b = [1, 1, 1]
b.splice(2, 1)
b // => [1, 1]
We are deleting the first element from a and the last from b, but of course there's no way of telling so just looking at the result.
In the case with the nulls, the same thing is happening. Some library (Angular) is trying to figure out which element you deleted, but there's no way of knowing. This is because null === null.
Now if you use an array of empty objects, for example, there would be a way of knowing. Since {} !== {}---because each time you cast a {} you are creating a unique object---, then you could know which element is missing in an array of empty objects. The case is similar with the array [1, 2, 3].
let a = [{}, {}, {}] // lets imagine that each object has a unique id
// and we have [{}#1, {}#2, {}#3]
let [obj1, obj2, obj3] = a
obj1 === obj2 // => false, because they have different ids.
a.splice(0, 1)
a // => [{}#2, {}#3]
a.includes(obj1) // => false, because {}#1 is no longer in a
So an alternative to using an array of nulls, would be to use an array of empty objects. I think that is why the code works for you when you use objects like { index: theIndex }. But of course all depends on how smart Angular is. I bet there is a more native way of deleting an element, as #KaiserKatze points out, "it's always a bad idea to directly remove or add elements in the array if it maps to your model."
You have to understand that when you are splicing the array you're only doing that--removing an element from an array. You're not removing the "form element" when splicing the array. Instead, some foreign code is reading the array and trying to figure out --under the hood-- what you intended to do.

Vue: How to remove object from array by it's value?

Is it's possible to remove object from array by it's value, not by index without iteration with for loop?
I tried to remove element with iteration, but it's look like that it do not remove iteration elements:
App.$refs.userContent.foo : [1,2,3,4]
console.log(App.$refs.userContent.foo);
App.$refs.userContent.foo.forEach(function(x,i)
{
App.$refs.userContent.foo.$remove(i);
});
console.log(App.$refs.userContent.foo);
Result:
[1, 2, 3, 4, __ob__: Observer]
[3, 4, __ob__: Observer]
Why it's do not remove all elements?
As you're removing elements from the array, you're changing the index of the ones that remain. If you wanted to remove all the elements, you'd do the following inside your .forEach() :
// Keep removing first array element until they're all gone
App.$refs.userContent.foo.$remove(0);
...but that would be strange to empty an array.
To answer your original question - No. You cannot remove an array element by its value in one step. You first have to find the index of the element, and then remove it by index. In vanilla JS, you can use .splice() to remove an element by its index:
// Remove 4th element from array
myArray.splice(3, 1);
You may want to use the filter function. For example:
[1,2,3,4].filter(x => x != 2)
to remove item from the array whose value is 2.
It has to iterate the array to find the element you want removed by value. So the answer is no.
You may be able to trick it into deceiving you about how it is doing this, but ultimately it will still have to find the element with the value you want removed. There are methods to optimize the search though if the array is sorted.
In Vue 1 there's a $remove method on arrays where that you can pass a reference to.
this.items.$remove(item)
I think that's gone in Vue 2 though. You can use indexOf instead of looping through. Something like:
var index = this.items.indexOf(item);
if (index > -1) {
this.items.splice(index, 1)
}
I had the same problem, i fix it putting :key in the v-for

What does empty array.slice(0).push(anything) mean?

I want to clone a new array from an existing one and push in an element.
Unfortunately, the existing array is an empty one, so it's like:
[].slice().push(65)
the output of above expression is 1.
Why is it 1?
Array#push() returns the length of the resultant array. Since you're pushing a single value onto an empty array, the length of the result will indeed be 1.
If you want to see the updated array as output, you'll need to save a reference to it since push() does not return a reference:
var arr = [].slice();
arr.push(65);
console.log(arr); // [ 65 ]
Changing my comment to an answer:
MDN push(): The push() method adds one or more elements to the end of an array and returns the new length of the array.
You need to do it in two steps, not one with that pattern.
var temp = [].slice();
temp.push(65);
console.log(temp);
If you want to do it in one line, look into concat()
var a = [1,2,3];
var b = [].concat(a,64);
console.log(b);

Find Javascript array length without deleted items

Just a simple question that I can't seem to find the answer to.
myarray.length()
The above will return the length including deleted items. How do I get the length without deleted items? Thanks
EDIT:
Thanks for the answers. I am deleting by writing 'delete myarray[0]' and this works well. Other sections of the script rely on the length() method to return the length including deletes. The splice method looks like what I want, so I'll try this
I think that you are deleting your array elements by using the delete operator.
This operator removes the element at the index you specify, but the array length is not affected, for example:
var a = [1,2,3];
delete a[0];
console.log(a); // results in [undefined, 2, 3]
If you want to delete the elements and shift the indexes, you can use the splice function:
var a = [1,2,3];
a.splice(0,1);
console.log(a); // [2, 3]
You could implement a simple function to remove elements in a given index:
Array.prototype.removeAt = function (index) {
this.splice(index,1);
};
If for some reason you do want to use sparse arrays (totally legitimate) but want to count the number of defined elements, you can just use reduce(), for example:
var arr = [1, 2, undefined, 3, undefined, undefined, 4];
arr.reduce(function(prev, curr) {
return typeof curr !== "undefined" ? prev+1 : prev;
}, 0); // evaluates to 4
reduce() is supported by all modern browsers, IE9+. For older browsers there's a polyfill and more info over at MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
You can use for..in loop, which ommits deleted items.
var a = [1,2,3,4,5];
delete a[0];
delete a[1];
for(var i=0;i<a.length;i++){}
console.log(i); //5
var j=0;
for(var i in a){j++;}
console.log(j); //3
John Resig (author of jQuery) wrote a function that (really) removes items from an array in Javascript. If you use this function instead of the delete operator, you should get an accurate count from the array after the deletion.
http://ejohn.org/blog/javascript-array-remove/

Why doesn’t deleting from a Javascript array change its length?

I have an array:
data.Dealer.car[0]
data.Dealer.car[1]
data.Dealer.car[2]
If I do this:
alert(data.Dealer.car.length);
delete data.Dealer.car[1];
alert(data.Dealer.car.length);
It gives me the same count each time. Does the removed element still exist?
If you want to remove an item, use the splice method:
alert(data.Dealer.car.length);
data.Dealer.car.splice(1, 1);
alert(data.Dealer.car.length);
But notice that the indices have changed.
JavaScript arrays aren't sparse, if you have a 0 and a 2, then element 1 must exist. Meaning the length is going to be 3.
Array.shift() would remove the first item from the array and make it shorter.
Array.pop() will remove the last item.
Building on what #Ray Hidayat posted:
JavaScript arrays are sparse. If you have an array of length 3, deleting the reference at [1] will simply "unset" that item, not remove it from the array, or update that array's length. You could accomplish the same with
myArray = [0, , 2, , , , ]; // length 6; last three items undefined
Here's a Fiddle:
http://jsfiddle.net/WYKDz/
NOTE: removing items from the middle of large arrays can be computationally intensive. See this post for more info:
Fastest way to delete one entry from the middle of Array()
I think you're looking for this:
var arr = [0,1,2,3,4];
alert( arr.splice( 2, 1 ) ); // alerts 2, the element you're removing
alert( arr ) // alerts 0,1,3,4 - the remaining elements
here's a MDC reference
Ok.. fixed this now as the array was still allocated.
I needed to basically do:
var newCar = new Array();
for (i = 0 ; i < tblSize -2; i ++)
{
newCar[i]=data.Dealer.car[i];
}
data.Dealer.car = newCar;

Categories

Resources