Reputation: 77
I am trying to implement a function to add an item to the beginning of an array without using the unshift or splice methods, just array.length. Everything I do so far just overwrites what is already existing at index 0. Any help would be appreciated!
LetsUnshift = function(array) {
for (var i = array.length - 1; i >0; i--) {
array[i +1] = array[i];
}
array[0] = item;
};
Upvotes: 2
Views: 5626
Reputation: 1
const array=[1,2,3]
const target=3
function addElementAtStarting(array, target){
return [target, ...array]
}
Upvotes: 0
Reputation: 9664
Just called the function instead and start it from arr.length-1
down to >= 0
as suggested in another answer
var item = 15, i, arr = [11, 23, 33, 54, 17, 89];
LetsUnshift(arr);
function LetsUnshift(arr) {
for (i = arr.length-1; i >= 0; --i) {
arr[i + 1] = arr[i];
}
arr[0] = item;
};
console.log(arr);
//OUTPUT: [15, 11, 23, 33, 54, 17, 89]
Upvotes: 0
Reputation: 66364
Keeping the same reference, you could use ES 6's Array.prototype.copyWithin
var arr = ['b', 'c', 'd'],
x = 'a';
++arr.length;
arr.copyWithin(1, 0);
arr[0] = x;
arr; // ["a", "b", "c", "d"]
You could reverse twice,
var arr = ['b', 'c', 'd'];
arr.reverse().push('a');
arr.reverse();
arr; // ["a", "b", "c", "d"]
You could re-push the whole thing,
var arr = ['b', 'c', 'd'],
a2 = arr.slice();
arr.length = 0;
arr.push('a');
Array.prototype.push.apply(arr, a2);
arr; // ["a", "b", "c", "d"]
You could iterate with while
, similar to your for
var arr = ['b', 'c', 'd'],
i = arr.length;
while (i-- > 0)
arr[i + 1] = arr[i];
arr[0] = 'a';
arr; // ["a", "b", "c", "d"]
If your goal is to create a new reference you could re-write either of those last two, e.g.
var arr = ['b', 'c', 'd'],
a2 = ['a'];
Array.prototype.push.apply(a2, arr);
a2; // ["a", "b", "c", "d"]
If we're just code-golfing,
var arr = ['b', 'c', 'd'],
a2 = Array.bind(null, 'a').apply(null, arr);
a2; // ["a", "b", "c", "d"]
Upvotes: 2
Reputation:
letsUnshift = function(array, itemToAdd) {
return array.reduce(function(newArray, value){
newArray.push(value);
return newArray;
}, [itemToAdd]);
};
letsUnshift([2,3,4], 1); //returns [1,2,3,4] and doesn't modify original array
Upvotes: 0
Reputation: 3240
This should work:
var LetsUnshift = function(array, item) {
for (var i = array.length - 1; i >=0; i--) {
array[i +1] = array[i];
}
array[0] = item;
};
The issue with your code is the condition i>0
, which prevents the first element from being shifted to the right.
Upvotes: 1