I have an array:
let a = {"data": [1,2,4]};
I have tried to delete two element at the same time:
a.data.splice(0, 1);
a.data.splice(2, 1);
But second deling can not find index 2 bacause splice rebuilds indexes. How to fix it?
You could start from the end to beginning of the array. In short start with the larger index. This keeps the the index pointing to the same element.
let a = { data: [1, 2, 4] };
a.data.splice(2, 1);
a.data.splice(0, 1);
console.log(a);
After removing first element the remaining element will shift 1 index up. So you could try:
let a = {"data": [1,2,4]};
a.data.splice(0, 1);// after this the data will have [2, 4]
a.data.splice(1, 1);
console.log(a);
If you want to remove the first and last elements of an array, you can use respectively shift() and pop() :
let a = {"data": [1,2,4]};
a.data.shift();
a.data.pop();
console.log(a);
Related
I am trying to remove 2 elements from end using splice method
This is what I am tryed
const arr = [3,4,5,6,7];
arr.splice(-1, 2)
I am expecting arr to be [3,4,5] but arr value is [3,4,5,6]
wanted to understand why it's behaving like this
From MDN
start
The index at which to start changing the array. If greater than the
length of the array, start will be set to the length of the array. If
negative, it will begin that many elements from the end of the array.
(In this case, the origin -1, meaning -n is the index of the nth last
element, and is therefore equivalent to the index of array.length -
n.) If array.length + start is less than 0, it will begin from index
0.
index -1 means from the last element so in our case, only the last element will be deleted.
You just start by the last index of the array and remove two items.
The result is an array without 7.
// -1 index
const arr = [3, 4, 5, 6, 7];
arr.splice(-1, 2);
console.log(arr);
The easiest way to do this will be to use arr.length
const arr = [3,4,5,6,7];
arr.splice(arr.length - 2)
console.log(arr)
First param tells to splice from which index it should delete all elements
const arr = [3,4,5,6,7];
const itemsToDelete = 2;
arr.splice(arr.length - itemsToDelete, itemsToDelete)
console.log('arr', arr);
I have an integer array which looks like this:
var _SingleScannedItemIds = [];
At some point I push some items inside the array itself like following:
_SingleScannedItemIds.push(checkbox_value);
Now my question here is:
How do I know if the array contains anything inside of it?
How do I remove integer numbers from it, based on which parameter?
Can someone help me out? I'm using jQuery...
How do I know if the array contains anything inside of it?
if(_SingleScannedItemIds.length == 0)
How do I remove integer numbers from it, based on which parameter?
_SingleScannedItemIds.splice(pos, 1)
What the above does is it removes 1 element from the position pos.
EDIT
delete _SingleScannedItemIds[pos]
Makes the _SingleScannedItemIds[pos] = undefined and then you can reassign it later with ex. _SingleScannedItemIds[0] = "apple". assuming pos = 0
jQuery Has nothing to do here.
Just use array.length array.splice()
Splice(index, numberOfElementsToRemove)
To get the length of an array:
var array = [0, 1, 2, 4];
console.log(array.length);
Removing items from an array is done by the key:
function remove(array, element) {
const index = array.indexOf(element);
array.splice(index, 1);
}
var array = [0, 1, 2, 4];
remove(array, 1); //removes number 1
console.log(array);
I have an Array like
var myArray = new Array;
I have to push some elements to array in such a way that the elements will be replaced with same index.
Example :
myArray.push(1);
myArray.push(2);
myArray.push(3);
so now
myArray[0] = 1
myArray[1] = 2
now when i will push element 3 then
myArray[0] will be replaced with 3 and myArray[1] will be replaced with 1 and the element 2 will be removed.
It will continue according to the number of elements pushed...
Can any body help me with this requirement...
push adds to the end of an array. If you want to add a value to the beginning of an array you can use unshift.
myArray.unshift(3);
You can then use pop to remove the last element:
arr.pop();
DEMO
However, what you might need, given that you need to remove the same number of elements from an array that you add is a function that uses concat and slice instead:
function pusher(arr, add) {
return add.concat(arr).slice(0, arr.length);
}
var arr = [1, 2, 3, 4];
var arr = pusher(arr, [5, 6]); // [5, 6, 1, 2]
DEMO
I think you need something in the lines of:
myArray.unshift(element);
myArray.pop();
Explanation:
unshift: inserts the element on position 0 and moves all other elements one position to the right
pop: removes last element from array
First of all sorry for the long title, I really didn't know how to word it better.
In the middle of solving _.shuffle in underscore, I encountered the use of splice. Here is my original code :
shuffle = function(array) {
var shuffledArray = [];
var total = array.length;
var copiedArray = array.slice();
while (total){
var randomNum = Math.floor(Math.random() * total);
shuffledArray.push(copiedArray.splice(randomNum,1));
total--;
}
return shuffledArray;
};
var originArray = [1, 2, 3, 4];
console.log(shuffle(originArray));
However after testing just I realized it will return each value inside a [ ], instead of just the value.
i.e.
[ [ 4 ], [ 3 ], [ 1 ], [ 2 ] ]
//instead of [ 4, 3, 1, 2]
When I changed this line (added '[0]' after the deleteCount in splice)
shuffledArray.push(copiedArray.splice(randomNum,1));
into this
//edited
shuffledArray.push(copiedArray.splice(randomNum,1)[0]);
the return array that I get is what I wanted, which is
[ 3, 1, 2, 4 ] //values are not in [ ]
Can someone explain how adding [0] after splice() makes the value not return in [ ] or why not having [0] does?
splice returns an array. When you push an array into an array, you get an array of arrays. By adding the [0], you push the first element of the array instead. This is no Javascript weirdness - it's perfectly reasonable.
As I suspected and was confirmed in the comments, you were using copiedArray.splice(randomNum,1)[0], not copiedArray.splice(randomNum,1[0]).
EDIT: That was the original question, and it was since edited.
And since splice returns an array (in your case, an array with one number), taking the first element of the array achieves exactly what you wanted.
Splice returns an array of the deleted elements. By adding [0] you are effectively selecting the first item in the returned array.
Try not to reinvent the wheel !
http://php.net/manual/fr/function.shuffle.php
If you really want to, try this in your while:
while (total){
var randomNum = Math.floor(Math.random() * total);
ShuffledArray[] = array[randomNum]; //add an item to next pos
unset(array[randomNum]); //remove the item added
array = array_values(array); //reindex array
total--;
}
Best of luck !
I'm wondering what is the fastest way in JavaScript to move an element from the beginning of an Array to the end. For example if we have
[8,1,2,3,4,5,6,7]
And we want: [1,2,3,4,5,6,7,8]
I want to move the first element to the end. I was thinking about switching element 0 with element 1, after that switching element 1 with element 2 and so on until the 8 is at the and (basically how bubblesort works). I was wondering if there is a faster way to bring the first element to the end.
I will be using small Arrays (around 10 elements), and I want to avoid shift() since it's pretty slow.
This is what I have now on chrome it's 45% faster than normal shift+push: http://jsperf.com/shift-myfunc
The arrays will have objects in them for a game.
Use the shift() and push() functions:
var ary = [8,1,2,3,4,5,6,7];
ary.push(ary.shift()); // results in [1, 2, 3, 4, 5, 6, 7, 8]
Example:
var ary = [8,1,2,3,4,5,6,7];
console.log("Before: " + ary);
ary.push(ary.shift()); // results in [1, 2, 3, 4, 5, 6, 7, 8]
console.log("After: " + ary);
Use shift and push
var a = ["a","b","c"];
var b = a.shift();
a.push(b);
or
var b = a.shift();
a[a.length] = b;
Edit Based on updated question
What is going to be the fastest? Really depends on content of the array and what browser/version!
Now what are the ways to remove the first index?
shift()
splice()
slice()
Now what are the ways to add to the last index?
push()
array[array.length]
concat() -- not even going to try
Other ways
for loop - make new array [going to be horrible on large arrays]
JSPerf:
http://jsperf.com/test-swapping-of-first-to-last
What is really the fastest?
What is the fastest really depends on what you are doing with the array. If you are just using the first index, it will be fastest just to make your code read an index and not shift the values. If you are using all the indexes, than just loop and through and when you get to the end start back at zero. Basic counters.
And here is a sweet ES6 version
let arr = [1,2,3,4,5,6]
const [first, ...rest] = arr;
arr = [...rest,first]
Use splice to get the first element
var first = array.splice(0,1);
Then push to make if the last.
Since the return value of the splice method is an array, you have to say
array.push(first[0]);
Working example here: JSFIDDLE
Just in case you want to put any element to the end:
var ary = [8,1,2,3,4,5,6,7];
ary.push(ary.splice(position, 1)[0]);
for position just wrap this in a forEach.
var a = [1,2,3,4,5,6,7,8];
var b= a[7];
var c = a.slice(1, 8);
c.push(b);
Edit: It's probably better to just shift, like epascarello did in his answer.
With ES20...
const newArr = [
...arr.slice(1),
arr[0]
];
one more flavour
var arr = [0, 1, 2];
arr = arr.concat(arr.shift())
concat can add not just a element but another array at the end or beginning
Updating the arrays moving elements from one extreme to the other:
const array = ['First', 'Second', 'Third', 'Fourth'];
const next = [...array]
next.push(next.shift())
console.log(next); // [ 'Second', 'Third', 'Fourth', 'First' ]
const prev = [...array]
prev.unshift(prev.pop())
console.log(prev); // [ 'Fourth', 'First', 'Second', 'Third' ]