javascript reverse an array without using reverse() - javascript

I want to reverse an array without using reverse() function like this:
function reverse(array){
var output = [];
for (var i = 0; i<= array.length; i++){
output.push(array.pop());
}
return output;
}
console.log(reverse([1,2,3,4,5,6,7]));
However, the it shows [7, 6, 5, 4] Can someone tell me, why my reverse function is wrong? Thanks in advance!

array.pop() removes the popped element from the array, reducing its size by one. Once you're at i === 4, your break condition no longer evaluates to true and the loop ends.
One possible solution:
function reverse(array) {
var output = [];
while (array.length) {
output.push(array.pop());
}
return output;
}
console.log(reverse([1, 2, 3, 4, 5, 6, 7]));

You can make use of Array.prototype.reduceright and reverse it
check the following snippet
var arr = ([1, 2, 3, 4, 5, 6, 7]).reduceRight(function(previous, current) {
previous.push(current);
return previous;
}, []);
console.log(arr);

In ES6 this could be written as
reverse = (array) => array.map(array.pop, [... array]);

No need to pop anything... Just iterate through the existing array in reverse order to make your new one.
function reverse(array){
var output = [];
for (var i = array.length - 1; i> -1; i--){
output.push(array[i]);
}
return output;
}
console.log(reverse([1,2,3,4,5,6,7]));
Edit after answer got accepted.
A link in a comment on your opening post made me test my way VS the accepted answer's way. I was pleased to see that my way, at least in my case, turned out to be faster every single time. By a small margin but, faster non the less.
Here's the copy/paste of what I used to test it (tested from Firefox developer scratch pad):
function reverseMyWay(array){
var output = [];
for (var i = array.length - 1; i> -1; i--){
output.push(array[i]);
}
return output;
}
function reverseTheirWay(array) {
var output = [];
while (array.length) {
output.push(array.pop());
}
return output;
}
function JustDoIt(){
console.log("their way starts")
var startOf = new Date().getTime();
for(var p = 0; p < 10000; p++)
{
console.log(reverseTheirWay([7,6,5,4,3,2,1]))
}
var endOf = new Date().getTime();
console.log("ran for " + (endOf - startOf) + " ms");
console.log("their way ends")
}
function JustDoIMyWay(){
console.log("my way starts")
var startOf = new Date().getTime();
for(var p = 0; p < 10000; p++)
{
console.log(reverseMyWay([7,6,5,4,3,2,1]))
}
var endOf = new Date().getTime();
console.log("ran for " + (endOf - startOf) + " ms");
console.log("my way ends")
}
JustDoIt();
JustDoIMyWay();

Solution to reverse an array without using built-in function and extra space.
let arr = [1, 2, 3, 4, 5, 6, 7];
let n = arr.length-1;
for(let i=0; i<=n/2; i++) {
let temp = arr[i];
arr[i] = arr[n-i];
arr[n-i] = temp;
}
console.log(arr);

Do it in a reverse way, Because when you do .pop() every time the array's length got affected.
function reverse(array){
var output = [];
for (var i = array.length; i > 0; i--){
output.push(array.pop());
}
return output;
}
console.log(reverse([1,2,3,4,5,6,7]));
Or you could cache the length of the array in a variable before popping out from the array,
function reverse(array){
var output = [];
for (var i = 0, len= array.length; i< len; i++){
output.push(array.pop());
}
return output;
}
console.log(reverse([1,2,3,4,5,6,7]));

You are modifying the existing array with your reverse function, which is affecting array.length.
Don't pop off the array, just access the item in the array and unshift the item on the new array so that the first element of the existing array becomes the last element of the new array:
function reverse(array){
var output = [],
i;
for (i = 0; i < array.length; i++){
output.unshift(array[i]);
}
return output;
}
console.log(reverse([1,2,3,4,5,6,7]));
If you'd like to modify the array in-place similar to how Array.prototype.reverse does (it's generally inadvisable to cause side-effects), you can splice the array, and unshift the item back on at the beginning:
function reverse(array) {
var i,
tmp;
for (i = 1; i < array.length; i++) {
tmp = array.splice(i, 1)[0];
array.unshift(tmp);
}
return array;
}
var a = [1, 2, 3, 4, 5];
console.log('reverse result', reverse(a));
console.log('a', a);

This piece allows to reverse the array in place, without pop, splice, or push.
var arr = [1, 2, 3, 4, 5];
function reverseArrayInPlace(arr2) {
var half = Math.floor(arr2.length / 2);
for (var i = 0; i < half; i++) {
var temp = arr2[arr2.length - 1 - i];
arr2[arr2.length - 1 - i] = arr2[i];
arr2[i] = temp;
}
return arr2;
}

As you pop items off the first array, it's length changes and your loop count is shortened. You need to cache the original length of the original array so that the loop will run the correct amount of times.
function reverse(array){
var output = [];
var len = array.length;
for (var i = 0; i< len; i++){
output.push(array.pop());
}
return output;
}
console.log(reverse([1,2,3,4,5,6,7]));

You're modifying the original array and changing it's size. instead of a for loop you could use a while
function reverse(array){
var output = [];
while(array.length){
//this removes the last element making the length smaller
output.push(array.pop());
}
return output;
}
console.log(reverse([1,2,3,4,5,6,7]));

function rvrc(arr) {
for (let i = 0; i < arr.length / 2; i++) {
const buffer = arr[i];
arr[i] = arr[arr.length - 1 - i];
arr[arr.length - 1 - i] = buffer;
}
};

const reverse = (array)=>{
var output = [];
for(let i=array.length; i>0; i--){
output.push(array.pop());
}
console.log(output);
}
reverse([1, 2, 3, 4, 5, 6, 7, 8]);

This happens because every time you do array.pop(), whilst it does return the last index in the array, it also removes it from the array. The loop recalculates the length of the array at each iteration. Because the array gets 1 index shorter at each iteration, you get a much shorter array returned from the function.

This piece of code will work without using a second array. It is using the built in method splice.
function reverse(array){
for (let i = 0; i < array.length; i++) {
array.splice(i, 0, array.splice(array.length - 1)[0]);
}
return array;
}

Here, let's define the function
function rev(arr) {
const na = [];
for (let i=0; i<arr.length; i++) {
na.push(arr[arr.length-i])
}
return na;
}
Let's say your array is defined as 'abca' and contains ['a','b','c','d','e','foo','bar']
We would do:
var reva = rev(abca)
This would make 'reva' return ['bar','foo','e','d','c','b','a'].
I hope I helped!

You can use .map as it is perfect for this situation and is only 1 line:
const reverse = a =>{ i=a.length; return a.map(_=>a[i-=1]) }
This will take the array, and for each index, change it to the length of the array - index, or the opposite side of the array.

with reverse for loop
let array = ["ahmet", "mehmet", "aslı"]
length = array.length
newArray = [];
for (let i = length-1; i >-1; i--) {
newArray.push(array[i])
}
console.log(newArray)

And this one:
function reverseArray(arr) {
let top = arr.length - 1;
let bottom = 0;
let swap = 0;
while (top - bottom >= 1) {
swap = arr[bottom];
arr[bottom] = arr[top];
arr[top] = swap;
bottom++;
top--;
}
}

function reverse(arr) {
for (let i = 0; i < arr.length - 1; i++) {
arr.splice(i, 0, arr.pop())
}
return arr;
}
console.log(reverse([1, 2, 3, 4, 5]))
//without another array

reverse=a=>a.map((x,y)=>a[a.length-1-y])
reverse=a=>a.map((x,y)=>a[a.length-1-y])
console.log(reverse(["Works","It","One","Line"]))

One of shortest:
let reverse = arr = arr.map(arr.pop, [...arr])

This is an old question, but someone may find this helpful.
There are two main ways to do it:
First, out of place, you basically push the last element to a new array, and use the new array:
function arrReverse(arr) {
let newArr = [];
for(let i = 0; i<arr.length; i++){
newArr.push(arr.length -1 -i);
}
return newArr;
}
arrReverse([0,1,2,3,4,5,6,7,8,9]);
Then there's in place. This is a bit tricky, but the way I think of it is like having four objects in front of you. You need to hold the first in your hand, then move the last item to the first place, and then place the item in your hand in the last place.
Afterwards, you increase the leftmost side by one and decrease the rightmost side by one:
function reverseArr(arr) {
let lh;
for(let i = 0; i<arr.length/2; i++){
lh = arr[i];
arr[i] = arr[arr.length -i -1];
arr[arr.length -i -1] = lh;
}
return arr;
}
reverseArr([0,1,2,3,4,5,6,7,8,9]);
Like so. I even named my variable lh for "left hand" to help the idea along.
Understanding arrays is massively important, and figuring out how they work will not only save you from unnecessarily long and tedious ways of solving this, but will also help you grasp certain data concepts way better!

I found a way of reversing the array this way:
function reverse(arr){
for (let i = arr.length-1; i >= 0; i--){
arr.splice(i, 0, arr.shift());
}
return arr;
}

Without Using any Pre-define function
const reverseArray = (array) => {
for (let i = 0; i < Math.floor(array.length / 2); i++) {
[array[i], array[array.length - i - 1]] = [
array[array.length - i - 1],
array[i]
];
}
return array;
};

let array = [1,2,3,4,5,6];
const reverse = (array) => {
let reversed = [];
for(let i = array.length - 1; i >= 0; i--){
reversed[array.length - i] = array[i];
}
return reversed;
}
console.log(reverse(array))

you can use the two pointers approach
example
function reverseArrayTwoPointers(arr = [1, 2, 3, 4, 5]) {
let p1 = 0;
let p2 = arr.length - 1;
while (p2 > p1) {
const temp = arr[p1];
arr[p1] = arr[p2];
arr[p2] = temp;
p1++;
p2--;
}
return arr;
}
to return [5,4,3,2,1]
example on vscode

let checkValue = ["h","a","p","p","y"]
let reverseValue = [];
checkValue.map((data, i) => {
x = checkValue.length - (i + 1);
reverseValue[x] = data;
})

function reverse(str1) {
let newstr = [];
let count = 0;
for (let i = str1.length - 1; i >= 0; i--) {
newstr[count] = str1[i];
count++;
}
return newstr;
}
reverse(['x','y','z']);

Array=[2,3,4,5]
for(var i=0;i<Array.length/2;i++){
var temp =Array[i];
Array[i]=Array[Array.length-i-1]
Array[Array.length-i-1]=temp
}
console.log(Array) //[5,4,3,2]

Related

hasPairsWithSum Google Interview Question

I solved this problem by iterating through the array then find the item when the sum equals to array[i] + item returning true otherwise returning false.
My Question is => How I can return the indices of those numbers that add up to sum not just true? Using the same code below:
function hasPairsWithSum(array,sum) {
for (let i = 0; i < array.length; i++) {
if (array.find((item) => {return sum === array[i] + item}
));
return true;
};
return false;
};
console.log(hasPairsWithSum([1,2,4,4],8))
Note: Time complexity must be less than O(n ^ 2).
JavaScript O(n) Solution.
function hasPairsWithSum(array, sum) {
const map = new Map ();
for(let i = 0; i < array.length; i++) {
let currVal = array[i];
if (map.has(currVal)) {
return [map.get(currVal),i]
}
// difference value = sum - current value
let diff = sum - currVal
map.set(diff,i)
}
};
console.log(hasPairsWithSum([2,2,4,4], 8))
Please refer this code.
function hasPairsWithSum(array,sum) {
let result = [];
for (let i = 0; i < array.length; i++) {
if (array.some((item, index) => {return i === index ? false : sum === array[i] + item}))
result.push(i);
};
return result;
};
console.log(hasPairsWithSum([1,2,4,4],8))
console.log(hasPairsWithSum([3,2,4],6))
console.log(hasPairsWithSum([0,4,3,0],0))
O(n) Soln ... using math concept a+b = n then if a is present in our array then need to find b = n - a is present or not ..
def hasPairsWithSum(array,sum):
d = {}
for i in range(len(array)):
if(array[i] in d):
d[array[i]].append(i)
else:
d[array[i]] = [i]
ans = []
for i in range(len(array)):
val = sum - array[i]
if(val in d):
if(d[val][0] == i):
if(len(d[val]) > 1):
ans.append((i,d[val][1]))
break
else:
continue
else:
ans.append((i,d[val][0]))
break
return ans
print(hasPairsWithSum([4, 4, 4, 4], 8))
O(nlogn) soln ....just store the index with elements .. then sort it by their values .. next step run a loop with complexity of O(n) [concept : Two pointers]
def hasPairsWithSum(array,sum):
arr = []
for i in range(len(array)):
arr.append((array[i],i))
arr.sort()
i = 0
j = len(array)-1
ans = []
while(i<j):
tmp_sum = arr[i][0] + arr[j][0]
if(tmp_sum == sum):
ans.append((arr[i][1] , arr[j][1]))
#add your logic if you want to find all possible indexes instead of break
break
elif(tmp_sum < sum):
i = i + 1
elif(tmp_sum > sum):
j = j - 1
return ans
print(hasPairsWithSum([1,2,4,4],8))
note : if you want to find all possible soln then these approaches will not work either add you own logic in while loop or another approach is use binary search with traversal on every element and store the indexes in set (worst case this will be O(n^2) as we have to find all possible values) Eg: [4,4,4,4,4,4] , sum = 8 and you want to print all possible indexes then we end up running it upto n^2 (why? reason: total possible solns. are 5+4+3+2+1 = n*(n-1)/2 ≈ n^2)
You have to iterate over the array elements checking at every iteration for every element of the array (except the last one) all the elements at the right of it like below:
function findIndexes(array, sum) {
const result = [];
for (let i = 0; i < array.length -1; ++i) {
for (let j = i + 1; j < array.length; ++j) {
if ((array[i] + array[j]) === sum) {
result.push([i, j]);
}
}
}
return result;
}
console.log(findIndexes([1, 2, 4, 4], 8));
console.log(findIndexes([3, 2, 4], 6));
Update:
It is possible to obtain a linear O(n) complexity using an auxiliary Map structure associating an integer value as key with as a value the list containing all the indexes of the elements in the array equal to the integer key like below:
function findIndexes(array, sum) {
const map = new Map();
const result = [];
for (let i = 0; i < array.length; ++i) {
const a = array[i];
const b = sum - a;
if (map.has(b)) {
for (const index of map.get(b)) {
result.push([index, i]);
}
}
const l = map.has(a) ? map.get(a) : [];
l.push(i);
map.set(a, l);
}
return result;
}
console.log(findIndexes([1, 2, 4, 4], 8));
console.log(findIndexes([3, 2, 4], 6));
console.log(findIndexes([1, 1, 1], 2));

Leetcode: Remove duplicates from sorted array (Javascript)

Why does my solution work in the console but not on leetcode?
var removeDuplicates = function(nums) {
let res = [];
for(let num of nums) {
if(res.includes(num) === false) {
res.push(num);
}
}
return res.length;
};
Console:
screenshot
Leetcode:
let arr = [1, 1, 2]
removeDuplicates(arr) // 3
You can try changing includes to indexOf, may be includes is not working in your environment. Also, instead of returning length you should return res.
Just in case you want to try another approach, you can look at Sets like below
var removeDuplicates = function(nums) {
return [...new Set(nums)]
};
console.log(removeDuplicates([1,1,2]))
console.log(removeDuplicates([1,1,2,3]))
You don't use sortness properly. Algorithmically it is more effective to compare item with previous one, so complexity is O(N).
Perhaps JS has some high-order function like Python groupby to make shorter code, but described method is definitely the best possible from algorithmical point of view.
ideone
var removeDuplicates = function(nums) {
let res = [];
let last = NaN
for(i=0; i<nums.length; i++) {
if(nums[i] != last) {
res.push(nums[i]);
last = nums[i];
}
}
return res.length;
};
let arr = [1, 1, 2]
print(removeDuplicates(arr))
>>2
Here is another solution you can try...
var removeDuplicates = function(nums) {
let p1 = 0,lastVal =nums[0] -1;
for (let i = 0; i < nums.length; i++) {
if (nums[i] != lastVal) {
nums[p1] = nums[i];
lastVal = nums[i]
p1 +=1;
}
}
nums.length = p1;
console.log(nums);
};
let arr = [1, 1, 2]
removeDuplicates(arr);
Click here to RUN

Javascript Heap's algorithm (non-recursive)

I have implemented Heap's non-recursive algorithm in JavaScript.
When checking permutations with console.log(arr) everything works as expected.
But when I try to push each permutation to a result array, then everything breaks up. It just returns result filled with last iteration permutation.
function generate(n, arr) {
function swap(item1, item2){
console.log(item1, item2);
let tmp = arr[item1];
arr[item1] = arr[item2];
arr[item2] = tmp;
}
var c = [];
var allPermutations = [];
for (let i = 0; i < n; i++) {
c[i] = 0;
}
console.log(arr);
allPermutations.push(arr);
for (let i = 1; i < n; i) {
if (c[i] < i) {
if (i % 2 == 0) {
swap(0, i);
} else {
swap(c[i], i);
}
console.log(arr);
allPermutations.push(arr);
c[i] += 1;
i = 1;
} else {
c[i] = 0;
i += 1;
}
}
return allPermutations;
}
console.log('result', generate(3, ["a", "a", "b"]));
The problem is that arrays are just references so when you push in the array you are just pushing a reference to it. So, on the next iteration you update the array and when you look at the final output, all the indexes will be the same since it is the same array.
So what can you do? clone it.
allPermutations.push(arr.slice(0));
Yep - its a reference problem. Alternative to epascarello's answer:
allPermutations.push([...arr]);

reverse array in place

Why won't this function reverseArrayInPlace work? I want to do simply what the function says - reverse the order of elements so that the results end up in the same array arr. I am choosing to do this by using two arrays in the function. So far it just returns the elements back in order...
var arr = ["a","b","c","d","e","f"]
var arr2 = []
var reverseArrayInPlace = function(array){
var arrLength = array.length
for (i = 0; i < arrLength; i++) {
arr2.push(array.pop())
array.push(arr2.shift())
}
}
reverseArrayInPlace(arr)
Here's a simpler way of reversing an array, using an in-place algorithm
function reverse (array) {
var i = 0,
n = array.length,
middle = Math.floor(n / 2),
temp = null;
for (; i < middle; i += 1) {
temp = array[i];
array[i] = array[n - 1 - i];
array[n - 1 - i] = temp;
}
}
You "split" the array in half. Well, not really, you just iterate over the first half. Then, you find the index which is symmetric to the current index relative to the middle, using the formula n - 1 - i, where i is the current index. Then you swap the elements using a temp variable.
The formula is correct, because it will swap:
0 <-> n - 1
1 <-> n - 2
and so on. If the number of elements is odd, the middle position will not be affected.
pop() will remove the last element of the array, and push() will append an item to the end of the array. So you're repeatedly popping and pushing just the last element of the array.
Rather than using push, you can use splice, which lets you insert an item at a specific position in an array:
var reverseArrayInPlace = function (array) {
var arrLength = array.length;
for (i = 0; i < arrLength; i++) {
array.splice(i, 0, array.pop());
}
}
(Note that you don't need the intermediate array to do this. Using an intermediate array isn't actually an in-place reverse. Just pop and insert at the current index.)
Also, interesting comment -- you can skip the last iteration since the first element will always end up in the last position after length - 1 iterations. So you can iterate up to arrLength - 1 times safely.
I'd also like to add that Javascript has a built in reverse() method on arrays. So ["a", "b", "c"].reverse() will yield ["c", "b", "a"].
A truly in-place algorithm will perform a swap up to the middle of the array with the corresponding element on the other side:
var reverseArrayInPlace = function (array) {
var arrLength = array.length;
for (var i = 0; i < arrLength/2; i++) {
var temp = array[i];
array[i] = array[arrLength - 1 - i];
array[arrLength - 1 - i] = temp;
}
}
If you are doing Eloquent Javascript, the exercise clearly states to not use a new array for temporary value storage. The clues in the back of the book present the structure of the solution, which are like Stefan Baiu's answer.
My answer posted here uses less lines than Stefan's since I think it's redundant to store values like array.length in variables inside a function. It also makes it easier to read for us beginners.
function reverseArrayInPlace(array) {
for (var z = 0; z < Math.floor(array.length / 2); z++) {
var temp = array[z];
array[z] = array[array.length-1-z];
array[array.length-1-z] = temp;
}
return array;
}
You are calling the function with arr as parameter, so both arr and array refer to the same array inside the function. That means that the code does the same as:
var arr = ["a","b","c","d","e","f"]
var arr2 = []
var arrLength = arr.length;
for (i = 0; i < arrLength; i++) {
arr2.push(arr.pop())
arr.push(arr2.shift())
}
The first statements get the last item from arr and places it last in arr2. Now you have:
arr = ["a","b","c","d","e"]
arr2 = ["f"]
The second statement gets the first (and only) item from arr2 and puts it last in arr:
arr = ["a","b","c","d","e","f"]
arr2 = []
Now you are back where you started, and the same thing happens for all iterations in the loop. The end result is that nothing has changed.
To use pop and push to place the items reversed in the other array, you can simply move the items until the array is empty:
while (arr.length > 0) {
arr2.push(arr.pop());
}
If you want to move them back (instead of just using the new array), you use shift to get items from the beginning of arr2 and push to put them at the end of arr:
while (arr2.length > 0) {
arr.push(arr2.shift());
}
Doing a reversal in place is not normally done using stack/queue operations, you just swap the items from the beginning with the items from the end. This is a lot faster, and you don't need another array as a buffer:
for (var i = 0, j = arr.length - 1; i < j; i++, j--) {
var temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
This swaps the pairs like this:
["a","b","c","d","e"]
| | | |
| +-------+ |
+---------------+
I think you want a simple way to reverse an array. Hope it will help you
var yourArray = ["first", "second", "third", "...", "etc"]
var reverseArray = yourArray.slice().reverse()
console.log(reverseArray)
You will get
["etc", "...", "third", "second", "first"]
With the constraints I had for this assignment, this is the way I figured out how to solve the problem:
var arr = ["a","b","c","d","e","f"]
var arr2 = []
var reverseArrayInPlace = function(array){
var arrLength = array.length
for (i = 0; i < arrLength; i++) {
arr2.push(array.pop())
}
for (i = 0; i < arrLength; i++) {
array[i] = arr2.shift()
}
}
reverseArrayInPlace(arr)
Thank you for all your help!
***** edit ******
For all of you still interested, I rewrote it using some help from this thread and from my own mental devices... which are limited at this point. Here is it:
arr = [1,2,3,4,5,6,7,8,9,10,11,12,13]
arr2 = ["a","b","c","d","e","f"]
arr3 = [1,2,3]
arr4 = [1,2,3,4]
arr5 = [1,2,3,4,5]
var reverseArrayInPlace2 = function(array) {
var arrLength = array.length
var n = arrLength - 1
var i = 0
var middleTop = Math.ceil(arrLength/2)
var middleBottom = Math.floor(arrLength/2)
while (i < Math.floor(arrLength/2)) {
array[-1] = array[i]
array[i] = array[n]
array[n] = array[-1]
// console.log(array)
i++
n--
}
return array
}
console.log(reverseArrayInPlace2(arr))
console.log(reverseArrayInPlace2(arr2))
console.log(reverseArrayInPlace2(arr3))
console.log(reverseArrayInPlace2(arr4))
console.log(reverseArrayInPlace2(arr5))
P.S. what is wrong with changing global variables? What would the alternative be?
Here is my solution with no temp array. Nothing groundbreaking, just shorter version of some proposed solutions.
let array = [1, 2, 3, 4, 5];
for(let i = 0; i<Math.floor((array.length)/2); i++){
var pointer = array[i];
array[i] = array[ (array.length-1) - i];
array[(array.length-1) - i] = pointer;
}
console.log(array);
//[ 5, 4, 3, 2, 1 ]
I know this is a old question, but I came up with an answer I do not see above. It is similar to the approved answer above, but I use array destructuring instead of a temporary variable to swap the elements in the array.
const reverseArrayInPlace = array => {
for (let i = 0; i < array.length / 2; i++) {
[array[i], array[array.length - 1 - i]] = [array[array.length - 1 - i], array[i]]
}
return array
}
const myArray = [1,2,3,4,5,6,7,8,9];
console.log(reverseArrayInPlace(myArray))
This solution uses a shorthand for the while
var arr = ["a","b","c","d","e","f"]
const reverseInPlace = (array) => {
let end = array.length;
while(end--)
array.unshift(array.pop());
return array;
}
reverseInPlace(arr)
function reverseArrayInPlace (arr) {
var tempArr = [];
for (var i = 0; i < arr.length; i++) {
// Temporarily store last element of original array
var holdingPot = arr.pop();
// Add last element into tempArr from the back
tempArr.push(holdingPot);
// Add back value popped off from the front
// to keep the same arr.length
// which ensures we loop thru original arr length
arr.unshift(holdingPot);
}
// Assign arr with tempArr value which is the reversed
// array of the original array
arr = tempArr;
return arr;
}

Inserting (splicing?) an Array into another Array without apply

Let's say we have two Arrays in JavaScript, [3,4,7] and [5,6].
Without sorting or using .apply, what is the best way to insert [5,6] into [3,4,7] at index 2 in order to achieve the resulting Array: [3,4,5,6,7]?
Don't know how you're defining "best way", but you can do this:
a.slice(0,2).concat(b,a.slice(2));
Unless you're saying you actually want to mutate the a Array, in which case you could do this:
var c = a.splice(2);
for (var i = 0; i < b.length + c.length; i++) {
a.push(i < b.length ? b[i] : c[i-b.length]);
}
This behavior of .splice() to split the Array in two parts may have issues in older IE that would need to be patched.
Or this would probably be better:
var c = b.concat(a.splice(2));
for (var i = 0; i < c.length; i++) {
a.push(c[i]);
}
Same caveat about .splice().
function splice(arrayOne, arrayTwo, index) {
var result = [];
for (var i = 0; i < arrayOne.length; i++) {
if (i == index) {
result = result.concat(arrayTwo);
}
result.push(arrayOne[i]);
}
return result;
}
Not really sure why you don't want to use the native methods, but here's a fairly naive solution with just loops:
function doInsert(index, items, arr) {
var insertLen = items.length,
current;
for (i = 0; i < insertLen; ++i) {
current = i + index;
arr[current + insertLen - 1] = arr[current];
arr[current] = items[i];
}
}
var arr = [3, 4, 7];
doInsert(2, [5, 6], arr);
console.log(arr);

Categories

Resources