javascript splice method and return confusion [duplicate] - javascript

This question already has answers here:
js. splice returns removed item?
(4 answers)
Closed 11 months ago.
So I was trying to create a javascript function to remove n elements from the beginning of an array, the following is the code:
function slasher(arr, howMany) {
arr.splice(0, howMany);
return arr;
}
slasher([1, 2, 3], 2);
Question:
Can someone explain to me why when I change the code inside the function to one line: return arr.splice(0, howMany);, the function would give me [1, 2] instead of [3]?
Thanks!

From docs of splice
Returns
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.
So you are actually getting the deleted elements array rather than the actual array.

Its because splice returns the elements removed but not the array with element removed.
var arr =[1,2,3]
var elementsRemoved = arr.splice(0,2);
elementsRemoved = [1,2] and arr would be [3].

Because splice() returns value and in the same time changes your array.
So when you return arr.splice() - you are returning what's returning this function, but when you return arr - you are returning your new array.

function slasher (arr, howMany){
return arr.splice(howMany, arr.length)
}
console.log(slasher([0,1,2,3,4],2))
splice syntax is splice(index, number of elemnets to be removed from that index)
or
function slasher (arr, howMany){
return arr.slice(howMany, arr.length)
}
console.log(slasher([0,1,2,3,4],3))

Related

Unable to remove a specific Item from array

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)

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.

I do not understand why .splice() is returning an empty array here

Would appreciate some feedback. I read the MDN, but I still don't get it. Thank you
function frankenSplice(arr1, arr2, n) {
return arr2.splice(n,0,arr1);
}
console.log(frankenSplice([1, 2, 3], [4, 5, 6], 1));
As correctly mentioned above, splice is usually used for adding single elements. Nothing, however, prevents it from working with arrays and adding those as elements to the other arrays. The reason for returning an empty array is that it returns array of deleted elements, not new array.
If you want to return updated array, do
function frankenSplice(arr1, arr2, n) {
arr2.splice(n,0,arr1);
return arr2;
}
splice is used for concatenating singular elements to an array.
If you want to combine arrays, first splice the element to one array:
var arr1 = [1,2,3,4]; // elements could be anything, I am just using integers here.
arr1.splice(n,0,element);
Then use concat if you want to combine two arrays.
var arr1 = [1,2,3,4];
var arr2 = [5,6,7,8];
var result = arr1.concat(arr2);
The question you are asking might not be the question you want answered, but from the MDN:
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.
You are expecting your function to return the spliced array, for which you need:
function frankenSplice(arr1, arr2, n) {
arr2.splice(n,0,arr1);
return arr2;
}
However, I suspect that #jshamble is right and you are not actually looking to use .splice().
Splice doesnt 'equal' the result, it directly writes it back to the variable. So instead of returning arr2.splice(n, 0, arr1); you have to write
arr2.splice(n, 0, arr1);
return arr2

Why does this now work as one return statement?

I am just curious, why does this block of code work...
function slasher(arr, howMany) {
arr.splice(0, howMany);
return arr;
}
slasher([1, 2, 3], 2);
But this does not? My desired outcome is "[3]"
function slasher(arr, howMany) {
return arr.splice(0, howMany);
}
slasher([1, 2, 3], 2);
Answering such questions is simply a matter of consulting a good documentation. I recommend Mozilla's MDN - Array.splice():
The splice() method changes the contents of an array by removing
existing elements and/or adding new elements.
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.
It tells us that this method changes the array in-place, i.e. myArray.splice() directly mutates / changes myArray instead of building a new array and returning that. The returned value is actually the list of removed elements.
function slasher(arr, howMany) {
arr.splice(0, howMany);
return arr;
}
slasher([1, 2, 3], 2);
This will first 'splice' the given array, which in essence will just remove the first howMany elements from the array (2). You then return the array (which is now different as it has had it's first 2 elements removed), hence [3].
function slasher(arr, howMany) {
return arr.splice(0, howMany);
}
slasher([1, 2, 3], 2);
This will return the result of the original splice. From the documentation where it says Return value (https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/splice?v=control), this will return the elements that were removed from the array, hence [1, 2].
#Sam, splice method changes the contents of an array (itself) by removing existing elements and/or adding new elements. Hence in the first code sample, you are getting [3].
However, it returns 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.
As a result in the second code sample, you get: [1,2].
This is because Splice returns an array containing the deleted elements, and not the remaining parts in the array. By returning arr, you returned the array after it was "slashed".
Source: Splice at MDN
Most functions in any Language are either Accessors, or Mutators. They either access a property or they change a property or structure. In this case, splice() is both. It's important to read documentation on all functions you use especially in JS as they sometimes will do more than one thing.
sometimes a function might be overloaded where one version is an accessor and the other is a mutator.
Any time you pass an array to a function make sure you know what might happen to the contents of the array.
Splice returns the removed elements while simultaneously changing the contents of the array. The return value is not the array you passed in. This is common across many languages to return a removed item from a data structure.

Swapping elements in an array of objects [duplicate]

This question already has answers here:
Javascript swap array elements
(33 answers)
Closed 9 years ago.
I have an array of objects and I want to swap the position of two elements in the array.
I tried this:
var tempObject = array.splice(index, 1, array[index + 1]);
array.splice(index+1, 1, tempObject);
But it doesn't seem to work properly as it results in some weird errors. For example, I am unable to use methods of the object. Calling array[x].getName results in an error.
Can any body lend a helping hand here?
Just in case it is important, I have used object.prototype to add the methods.
The bug in your code is that splice returns an array of items, not a single item. Since you are extracting a single item, you could do:
var tempObject = array.splice(index, 1, array[index + 1])[0]; // get the item from the array
array.splice(index+1, 1, tempObject);
This answer provides a shorter version, also using splice:
array[index] = array.splice(index+1, 1, array[index])[0];
Another very interesting answer is both short and fast:
function identity(x){return x};
array[index] = identity(array[index+1], array[index+1]=array[index]);
JSFIDDLE
var array_of_numbers = [5,4,3,2,1,0],
swap = function(array,a,b){var tmp=array[a];array[a]=array[b];array[b]=tmp;};
swap(array_of_numbers,0,4);
// array_of_numbers now is [1,4,3,2,5,0]
Or you can do add the function to the Array.prototype:
JSFIDDLE
Array.prototype.swap = function(a,b){ var tmp=this[a];this[a]=this[b];this[b]=tmp;};
var array_of_numbers = [5,4,3,2,1,0];
array_of_numbers.swap(0,4);
// array_of_numbers now is [1,4,3,2,5,0]

Categories

Resources