function reverse(array,item){
let word = Math.ceil(array.length/2)
return array.splice(word,0,item)
}
console.log(reverse([1,2,4,5,6],3))
I was wondering why I'm getting a an empty array when the I call the function, instead of [1,2,3,4,5,6]?
Array#splice returns the items of the second parameter's count, the items who are deleted.
For returning the array, you need to return then array and not the spliced items.
function reverse(array, item) {
let word = Math.ceil(array.length / 2);
array.splice(word, 0, item);
return array;
}
console.log(reverse([1, 2, 4, 5, 6], 3));
splice does not return a new array, it modifies the input array. you need to return explicitly
function reverse(array,item){
let word = Math.ceil(array.length/2)
array.splice(word,0,item)
return array
}
console.log(reverse([1,2,4,5,6],3))
array.splice(...) does not return a new array, it modifies the input array. Per MDN, its return value is:
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.
If your intention is to create a function that inserts without modifying the original array, here's a good example: https://stackoverflow.com/a/38181008/1266600.
splice() changes the original array whereas slice() doesn't.
If you don't want to alter the original array, use slice.
function reverse(array,item){
let word = Math.ceil(array.length/2)
return [].concat(array.slice(0,word - 1), item, array.slice(word - 1));
}
console.log(reverse([1,2,4,5,6],3))
Related
Here is my code:
let num = 0.0134;
console.log(num.toString().split('').splice(3).splice(1, 0, '.'))
The console.log returns an empty array.
I want it to return '1.34'. What am I doing wrong?
If you see the reference for Array.prototype.splice on mdn:
The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place
Return Value: An array containing the deleted elements.
At the end of your code, when you do .splice(1, 0, '.'), it deletes 0 elements so it will return an empty array.
I'm assuming you want to get the previous array with the '.' element inserted in the first position. For that you'll want to do:
const arr = num.toString().split('').splice(3);
arr.splice(1, 0, '.');
console.log(arr)
And If you want to join it to a string just use arr.join('')
Anyway, for your use case, you could just use the * multiplication operator rather than converting to a string array and attempting to manipulate that.
You can simply do:
let num = 0.0134;
console.log(num * 100);
Suppose I have an array var arr = [1,2,3] and if I do var result = arr.filter(callback) I want value of result would be [2,4,6] by the use of filter. I want to only define callback function in order to do so. It can be easily done with map but I want to use only filter.
Array.prototype.filter only filters existing values in an array, effectively creating a new array that can hold the same values, their subset, or an empty array, based on the filtering function.
You could do it using filter():
const arr = [1, 2, 3];
arr.filter((c, i) => {
arr[i] = +arr[i] * 2;
return true;
});
console.log(arr)
we are always returning true, so filter() makes no sense in this case.
As stated many times, there is no reason why you should do it.
It is impossible to do it like map because map returns a new array. You can either alter on the original array or you have to make a clone of the original array so you do not change it.
// this modifies the orginal array
var arr1 = [1,2,3]
arr1.filter((v,index,arr)=>{
arr[index] = v * 2;
return true
})
console.log(arr1)
// or you can clone it and do the same thing
// this modifies the cloned array
var arr2 = [1,2,3]
var arr3 = arr2.slice()
arr3.filter((v,index,arr)=>{
arr[index] = v * 2;
return true
})
console.log(arr2, arr3)
So no, you can not recreate map with filter since you HAVE to modify the original array or cheat and use a copy of the array.
So I'm not sure I understand the second part of your question, but as for the first part:
The callback for filter has three arguments, two of which are optional.
The first argument is the current element in the traversal, and the second and third arguments (the optional ones) are the 0-based index of the current element, and a reference to the original array.
This third parameter is useful for what you're trying to do.
let myArr = [1, 2, 3];
myArr.filter((el, ind, orig) => {
orig[ind] = orig[ind] + 1; // Or, whatever map logic you want to use
return true; // since a Boolean condition must be returned here
});
This way you can do it without even even having to break the scope of the function!
If you want to do it without necessarily having a variable to originally call filter on (you do have to pass an array), you can use the prototype and the call method:
Array.prototype.filter.call([1, 2, 3], (el, ind, orig) => {
orig[ind] = orig[ind] + 1;
return true;
});
I know code below is worst.However, I want to know why?
const hello = (list) => {
list = list.map((item, index) => {
if (index === 3) {
list.splice(index, 1)
}
return item
})
console.log(list)
}
hello([1, 2, 3, 4])
why the result is [1,2,3,4],not [1,2,3]?
thanks very much!
If you see the polyfill section in the Array.prototype.map docs on how the map is implemented, you would see that the array on which the map is called is copied initially into a variable.
A loop is then used to iterate through the elements of the copied array till it reaches the length of the array. In each iteration the callback function which you supply is called to transform each element of the array and put inside a new array which is then returned from the map function.
So even though you mutate the array after you call the map it will still refer the original data and not the new one.
If you want to skip over certain elements you should use filter instead of map.
const hello = (list) => {
list = list.filter((item, index) => {
return index !== 3;
})
console.log(list)
}
hello([1, 2, 3, 4])
.map creates a new array, created from the return value of each iteration over the old array. Your
return item
inside the .map means that the new array created will be exactly the same as the original array (a shallow copy).
Each element of an array will be called with .map's callback even if the array gets changed in the meantime - the fact that the original list array has gotten spliced doesn't have any visible effect, because the .map already has a reference to every item that was in the array at the beginning, when .map was called.
If you had spliced item 3 before mapping, the result would indeed be [1, 2, 3]:
const hello = (list) => {
list.splice(3, 1);
list = list.map((item, index) => {
return item
})
console.log(list)
}
hello([1, 2, 3, 4])
I have an array like this:
var CutRoadArray = [
['Location', '_Location'],
['Applicant Info', '_ApplicantInfo'],
['Details', '_ApplicationDetails'],
['Bond Info', '_BondInfo'],
['Attachments', '_Attachments'],
['Review', '_ReviewA']
];
I am trying to replace the last item, with a different entry.
The code I have so far goes like below:
var newreviewElem = ['Review', '_ReviewB'];
var index = CutRoadArray.lastIndexOf('_ReviewA');
CutRoadArray.splice(index, 0, newreviewElem);
console.log(CutRoadArray);
This is however not working. What am I doing wrong ?
https://jsfiddle.net/yygLdo0o/
There are actually two things wrong with your answer.
The first is that you need to grab the correct index. If you're replacing the last item, just grab the array.length.
The second is that you need to indicate how many you're replacing:
CutRoadArray.splice(CutRoadArray.length - 1, 1, newreviewElem);
The second argument in splice should be 1, not 0.
This will replace the last element of any size array, because it doesn't rely on an item in the array being in a specific location or a particular index.
CutRoadArray.length - 1 is grabbing the number of items in the array, but since splice uses a zero based index, you have to subtract one to get the index of the last item in the array.
The second argument (bolded below), tells splice to replace a single item.
Documentation about splice
CutRoadArray.splice(CutRoadArray.length - 1, 1, newreviewElem);
And then finally, the last argument is the item to actually add to the array.
Working fiddle
It should be:
CutRoadArray.splice(index, 1, newreviewElem);
The second parameter indicates how many items should be replaced.
Your
CutRoadArray.lastIndexOf('_ReviewA');
will, of course, not find anything since CutRoadArray contains arrays, not strings.
for(var iter = 0; iter < CutRoadArray.length; iter++) {
if (CutRoadArray[iter][1] == '_ReviewA') {
CutRoadArray[iter] = newreviewElem;
break;
}
}
If you want to replace the element, use
CutRoadArray.splice(index, 1, newreviewElem);
The second parameter of splice is the deleteCount, 0 means no item will be removed.
An other problem with your code is that
CutRoadArray.lastIndexOf('_ReviewA');
will always return -1, as CutRoadArray is an array of arrays, meaning every element of it is an array, it doesn't have an element which is '_ReviewA'. (That's an element of one of CutRoadArray's elements.)
I suggest to iterate over the main array and search in the nested array for the wanted index. After found it is simple to replace the nested array at the index like array[index] = replace;. If not found, the the array is pushed to the end.
function replace(array, find, replace) {
var index;
if (array.some(function (a, i) {
if (~a.indexOf(find)) {
index = i;
return true;
}
})
) {
array[index] = replace;
} else {
array.push(replace);
}
}
var cutRoadArray = [
['Location', '_Location'],
['Applicant Info', '_ApplicantInfo'],
['Details', '_ApplicationDetails'],
['Bond Info', '_BondInfo'],
['Attachments', '_Attachments'],
['Review', '_ReviewA']
];
replace(cutRoadArray, '_ReviewA', ['Review', '_ReviewB']);
document.write('<pre>' + JSON.stringify(cutRoadArray, 0, 4) + '</pre>');
I have an array:
array = ['mario','luigi','kong']
I call its splice function to remove all items before an index:
array.splice(1) //-> ['luigi','kong']
I'm just wondering if there is a function similar to splice to remove all items after an index:
pseudo code
array.mirrorsplice(1) //-> ['mario','luigi']
Use Array.length to set a new size for an array, which is faster than Array.splice to mutate:
var array = ['mario','luigi','kong', 1, 3, 6, 8];
array.length=2;
alert(array); // shows "mario,luigi";
Why is it faster? Because .splice has to create a new array containing all the removed items, whereas .length creates nothing and "returns" a number instead of a new array.
To address .splice usage, you can feed it a negative index, along with a huge number to chop off the end of an array:
var array = ['mario','luigi','kong'];
array.splice(-1, 9e9);
alert(array); // shows "mario,luigi";
Though assigning a shorter value to the array length(as #dandavis said) is the fastest and simplest way to remove trailing element from an array, you can also do that using a similar method like splice which is known as slice.
Like following:
array = ['mario', 'luigi', 'kong'];
array = array.slice(0, 2); //Need to assign it to the same or another variable
console.log(array); //["mario", "luigi"]
As you can see you need to store the returned value from slice method. To understand 'why', here are the major distinction between slice and splice method:
The splice() method returns the removed item(s) in an array and slice() method returns the selected element(s) in an array, as a new array object.
The splice() method changes the original array and slice() method doesn’t change the original array.
To remove all items after an index:
var array = ['mario','luigi','kong'],
index = 1; // your index here
array = array.splice(index + 1, array.length - (index + 1) );
// 3 - (1+1) = 1
// 1 is the remaining number of element(s) in array
// hence, splice 1 after index
Result:
['mario', 'luigi']
You need to +1 since splice starts removing at the index.
I think you misunderstood the usage of Array.prototype.splice(). It already does what you asked for (remove everything after an index, read below paragraph for correction) and it does return the deleted values. I think you got confused with the returned value as the current value of the array.
Array.prototype.splice() however, removes the provided index value too, which is basically equivalent of setting the length of the array. So if you call it as array.splice(2), it'll set the length to 2 and everything including the values at index 2 and after will be deleted. This is provided that the current length of the array is greater than the first parameter provided to Array.prototype.splice().
For example:
const array = ['mario','luigi','kong'];
const deletedItem = array.splice(1);
console.log(array); // ['mario']
console.log(deletedItem); // ['luigi','kong']
For more information: refer to the MDN doc.
You can use splice. Here is a demo.
var array = ['mario','luigi','kong']
To remove all the elements after an index:
var removedElement = array.splice(index, array.length)
removedElement will have the list of elements removed from the array.
example:
let index = 2;
var removedElement = array.splice(2, array.length);
removedElement = ["kong"];
array = ["mario", "luigi"];