Replacing Array element with same index in javascript - javascript

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

Related

javascript splice method removing elements from end

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);

Javascript Remove an array element and reorder the remaining elements

I have an array with a fixed length of 6.
I want to remove the first element from the array, then shift all the elements left by 1, but the length of the array should remain as 6 (the 6th position of the array can be undefined)
I tried using splice but the array length was reduced to 5 which is not what I want to happen.
What is the best approach to achieve the above?
You can use Array.prototype.slice (which does not mutate the original array unlike splice) to take a copy of the array from the 1st position.
Then use Array.from to get a new array from the copy and mention the length property value of the old array:
const arr = [1, 2, 3, 4, 5, 6]
const newArr = Array.from({length: arr.length, ...arr.slice(1)});
console.log(newArr);
You can shift the first element, then push undefined, as shown below:
const array = [1, 2, 3, 4, 5, 6]
array.shift()
array.push(undefined)
console.log(array)

Return a new array with the first and last element of the passed array

I am not sure what I am missing. Need the new array to return the first and last element of the passed array.
var firstAndLast = function(array){
var newArray = new Array();
newArray [0] = array[0]
newArray [1] = array[3]
return plate;
}
For Example:
var array = ['one', 3, 'cool', 4];
firstAndLast(array); // returns ['one', 4]
You need to access the first and last element, and return that in an array. I'm not sure where plate comes from, but in general your function is 'correct' in the sense that you create a new array and set the first and second elements to the first and last elements of the passed array. You just need to return newArray.
But what if the the 4th element isn't the last one in the array? Then you'd have to make it more general:
var array = ['one', 3, 'cool', 4];
var firstAndLast = function(arr) {
return [arr[0], arr[arr.length - 1]]; //No need for new Array(), and you can just assign items in positions inline
}
console.log(firstAndLast(array));
The above code reduces the function into 3 lines, as it returns an array literal, with the first element as arr[0], the first element of the passed array. The second element is arr[arr.length - 1], which is the last element. Consider this:
[1, 2, 3, 4, 5]
The length currently is 5, and the last element is accessed by arr[4]. Now, just subtract one from the length to get 4, and access the last element. arr[arr.length - 1] in this case would yield 5.

Javascript delete operator on array list element

I am confused about delete operator use on array element.
I found that delete can be used with array elements and it removes the element but doesn't update array length , so basically that element is replaced with undefined.But when i tested it I found that it replaces it with blank.
var test = new Array()
delete test[id];
So i have 3 points regarding this
test[id] id in this is element or index of element, as I read that id can be both. But when I tested it , I found its working only when i pass index.
What if the array has no element and I try to delete by passing any value like delete test[3]?
when i delete an element then it replaces that with undefined or blank?
Don't use delete on array, use splice()
delete will not remove the element actually from array. It'll just set the value to undefined
delete does not alter the length of array
delete Demo
var arr = [1, 2, 3, 4, 5];
delete arr[2];
document.write(arr);
console.log(arr);
document.write('<br />Length: ' + arr.length);
Use splice()
The splice() method changes the content of an array by removing existing elements and/or adding new elements.
splice() will return silently, if you passed an out of bound index to remove.
arr.splice(indexToDelete, 1);
splice() Demo
var arr = [1, 2, 3, 4, 5];
arr.splice(2, 1);
arr.splice(100, 1); // For out of bounds index, it fails silently
document.write(arr);
console.log(arr);
document.write('<br />Length: ' + arr.length);

Fastest way to move first element to the end of an Array

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' ]

Categories