Unable to remove a specific Item from array - javascript

I have a simple array as
arr=[{"name":"sam","value":"1"},{"name":"ram","value":"2"},{"name":"jam","value":"3"},{"name":"dam","value":"4"}]
I need to remove the first index from this array and it should be of below type
[{"name":"sam","value":"1"},{"name":"jam","value":"3"},{"name":"dam","value":"4"}]
I tried splice as below
arr.splice(1,1)
But it is giving response {"name":"ram","value":"2"}
how to get [{"name":"sam","value":"1"},{"name":"jam","value":"3"},{"name":"dam","value":"4"}]
It might be very simple question but Im stuck here from sometime.can someone plz help

I think you taking the returning value of Array.prototype.splice().
Array.prototype.splice() returns an array containing the deleted elements.
The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place
arr=[{"name":"sam","value":"1"},{"name":"ram","value":"2"},{"name":"jam","value":"3"},{"name":"dam","value":"4"}]
arr.splice(1,1)
console.log(arr);

You can compare the difference methods. Be aware if you need change the array or just get a copy to keep with the original one.
Attention: The first array index is 0, not 1. The index one is the second element of the array
The splice method return the element removed from array. That's the reason why you've got the second element from array in your test
Doc: https://bytearcher.com/articles/how-to-delete-value-from-array/
In your question you got the second index that is 1, in order to get the values that was shown, I'll use the index 1 as well.
//DELETE
arr=[{"name":"sam","value":"1"},{"name":"ram","value":"2"},{"name":"jam","value":"3"},{"name":"dam","value":"4"}]
delete arr[1];
console.log("using delete",arr)
//SPLICE METHOD
arr=[{"name":"sam","value":"1"},{"name":"ram","value":"2"},{"name":"jam","value":"3"},{"name":"dam","value":"4"}]
let firstElement = arr.splice(1,1)
console.log("using splice",arr)
console.log("the method splice return the element removed from array",firstElement )
//FILTER METHOD
arr=[{"name":"sam","value":"1"},{"name":"ram","value":"2"},{"name":"jam","value":"3"},{"name":"dam","value":"4"}]
let copyArr = arr.filter((element, index)=>index !== 1)
console.log("extra: using filter (will return a array copy)",copyArr)

Related

How can I compensate for a removed element in an array iteration that is still in progress? [duplicate]

This question already has answers here:
Filter and delete filtered elements in an array
(10 answers)
Closed 3 years ago.
I am iterating over an array of strings using forEach(), and testing each element's length to determine wether it is even or odd. If the length of the string is even, it will be removed using splice().
My input and output are shown below, and as you can see even though (i think) my conditions are correct, in my return array, I still get an even, two character word - which should have been spliced out.
Code:
function filterOddLengthWords(words) {
words.forEach(function(element, index) {
if (element.length%2===0) {
words.splice(index, 1);
}
})
return words;
}
var output = filterOddLengthWords(['there', 'it', 'is', 'now']);
console.log(output); // --> [ 'there', 'is', 'now' ]
I understand where the error is, but I just don't know how to compensate for it. I could possibly rewrite this by creating an empty array at the beginning of the function, and then testing each element against the inverse condition, using the push() method to add each positive to the empty array. However, that is more inefficient and I'm curious to see if my way is possible. Thanks for the answers in advance.
By splicing an array, you change the index, but forEach takes the elements in advance and the old indices.
Usually by using splice, the iteration is started from the end and if some item is remoce, the index remains for the items before.
You could filter the array.
function filterOddLengthWords(words) {
return words.filter(function(element) {
return element.length % 2;
});
}
var output = filterOddLengthWords(['there', 'it', 'is', 'now']);
console.log(output);
The problem with splicing the array in the forEach() is that when you splice() on the array at index 1 which has the element it the element at index 2 is is moved to index 1.
So in the next iteration when the index is 2 in the callback the element at the index 2 of the array is the value now instead of the element is. As now is odd it is kept but the element is is completely skipped.
Using Array.prototype.filter will work here as it does not modify the original array but instead collects the valid results into a new array.

Why is filter method not deleting all elements of the array?

this.arol.filter(x=>x.length!==0
?(this.arol.splice(this.arol.indexOf(x),1))
:!true)
I was trying to change it many different ways, but it still does not delete all elements of the array, it always leaves 1 or 2 behind deleting most of them.... I think the problem is with the condition... We are checking if the length of array elements is not 0 (which are all strings)...
Don't try to splice while filtering - instead, return from the filter callback a truthy or falsey value, depending on whether you want to include the item being iterated over in the new array, and use the resulting array that gets returned from .filter:
this.arol = this.arol.filter(x => x.length !== 0);
^^^^^^^^^^^^
If you want to maintain same outer array reference and mutate original you can splice in a loop if you work from end to start so as not to affect indexing you haven't arrived at yet as you change the array length:
const arr = [[1],[],[2]]
arr.reduceRight((_,c,i) => c.length || !!arr.splice(i,1))
console.log(arr)
The problem is you are trying to splice at the same time you are using filter. Filter does not remove elements from your array, it creates a new array with the filtered data, as described here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
You can assign the result to the same array as suggested by CertainPerformance.
If Splice is removed from that code then it will not delete elements. this.arol.splice(this.arol.indexOf(x),1) here it will iterate through every element inside that array and x will be current iteration which will splice from the array as you have written splice method. Remove splice it will work fine.

Javascript slice isn't giving me correct array length values

Why does it say length 1 instead of 4?
The following is what I'm trying to push and slice. I try and append items.image_urls and slice them into 5 each.
items.image_urls is my dictionary array.
var final_push = []
final_push.push(items.image_urls.splice(0,5))
console.log(final_push.length)## gives me 1...?
var index = 0
final_push.forEach(function(results){
index++ ##this gives me one. I would need 1,2,3,4,5,1,2,3,4,5. Somehting along that.
}
items.image_urls looks like this:
It's an iteration of arrays with image urls.
In your example items.image_urls.splice(0,5) returns an array of items removed from items.image_urls. When you call final_push.push(items.image_urls.splice(0,5));, this whole array is pushed as one item to the final_push array, so it now looks like [["url1", "url2", "url3", "url4", "url5"]] (2-dimensional array). You can access this whole array by calling final_push[some_index].
But what you want instead is to add every element of items.image_urls.splice(0,5) to the final_push. You can use a spread operator to achieve this:
final_push.push(...items.image_urls.splice(0,5));
Spread syntax allows an iterable such as an array expression or string
to be expanded in places where zero or more arguments (for function
calls) or elements (for array literals) are expected
This is exactly our case, because push() expects one or more arguments:
arr.push(element1[, ...[, elementN]])
And here is an example:
let items = {
image_urls: ["url1", "url2", "url3", "url4", "url5", "url6", "url7", "url8", "url9", "url10"]
};
let final_push = [];
final_push.push(...items.image_urls.splice(0,5));
console.log(final_push.length);
console.log(JSON.stringify(final_push));
console.log(JSON.stringify(items.image_urls));
Note: do not confuse Array.prototype.slice() with Array.prototype.splice() - the first one returns a shallow copy of a portion of an array into a new array object while the second changes the contents of an array by removing existing elements and/or adding new elements and returns an array containing the deleted elements.
That seems to be a nested array. So if you would access index 0, and then work on that array like below it will probably work:
console.log(final_push[0].length); //should print 4
The author is mixing up splice and slice. Probably a typo :)
You start at the beginning (0) and then delete 5 items.

Javascript: How can I use splice() on an array to move a specific word?

This is the code I have - can you please tell me what is wrong? I would like to remove a specific word from the array using splice, in this case "tree".
var array = ['dog', 'man', 'tree']
array.splice(array.indexOf('tree'));
The second argument to splice is the number of items to delete.
array.splice(array.indexOf('tree'), 1);
otherwise all following elements are deleted.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice
Just filter it:
const withoutTree = array.filter(word => word !== 'tree')
You also have to provide an argument specifying how many items to delete. Otherwise, all elements from the specified start index will be removed.
array.splice(array.indexOf('tree'), 1);
Javascript splice method works with index to be deleted and item to be deleted.
In your case-
var newArray = array.splice(2,1);
console.log(newArray);// outputs ['dog','man']
Here 2 is the index of the element to be deleted which is 'tree' in your case and the second argument defines the number of element to be deleted.

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

Categories

Resources