Best way to concatenate an array prefix and an array reversed prefix - javascript

Given two arrays and two indices, I need to concatenate the prefix of the first array and the reversed prefix of the second array.
For example:
// Input
arr1 = [1,2,3,4,5,6,7,8,9];
arr2 = [10,11,12,13,14,15];
ind1 = 6;
ind2 = 3;
// Output
arr = [1,2,3,4,5,6,12,11,10];
Here is my code:
function Concat(arr1,arr2,ind1,ind2) {
let arr = [];
for (let n = 0; n < ind1; n++)
arr.push(arr1[n]);
for (let n = ind2; n > 0; n--)
arr.push(arr2[n-1]);
return arr;
}
I am looking for a better (cleaner / faster / simpler / more elegant) way to do this. What can I try?

You can try something like this:
Note: This will not be faster than current approach. This is just little cleaner.
function Concat(arr1,arr2,ind1,ind2) {
return [].concat(arr1.slice(0, ind1), arr2.slice(0, ind2).reverse());
}
arr1 = [1,2,3,4,5,6,7,8,9];
arr2 = [10,11,12,13,14,15];
ind1 = 6;
ind2 = 3;
console.log(Concat(arr1, arr2, ind1, ind2))
As suggested, there will not be huge performance impact. You can check the difference js-perf sample.
An alternate approach if you have ability to override input structure.
Since we are expecting array of object in custom order, it will be easy to make it generic. Assuming the structure to be:
Please mind the syntax as I'm heavily working on Typescript, it is easier for me to write in that syntax.
interface ConcatObject {
value: Array<any>;
endIndex: number;
isReverse: boolean
}
when you read, it makes code easier to read and simpler to make it generic.
function Concat(arr) {
return arr.reduce(function(acc, cur) {
var temp = cur.value.slice(0, cur.endIndex);
if (cur.isReverse) {
temp = temp.reverse();
}
return acc.concat(temp);
}, []);
}
var data = [{
value: [1, 2, 3, 4, 5, 6, 7, 8, 9],
endIndex: 6
},
{
value: [10, 11, 12, 13, 14, 15],
endIndex: 3,
isReverse: true
}
]
console.log(Concat(data))

If ES6 is not a problem, you can do it by the code below:
var arr1 = [1,2,3,4,5,6,7,8,9];
var arr2 = [10,11,12,13,14,15];
var ind1 = 6;
var ind2 = 3;
var output = [...arr1.slice(0, ind1), ...arr2.slice(0, ind2).reverse()];
console.log(output);
If you don't want to use ES6 spread syntax, you can use array.prototype.concat :
var arr1 = [1,2,3,4,5,6,7,8,9];
var arr2 = [10,11,12,13,14,15];
var ind1 = 6;
var ind2 = 3;
var output = arr1.slice(0, ind1).concat(arr2.slice(0, ind2).reverse());
console.log(output);

Simplest solution
Code:
// declarations
arr1 = [1,2,3,4,5,6,7,8,9];
arr2 = [10,11,12,13,14,15];
ind1 = 6;
ind2 = 3;
var arr = [];
// changing length as per index
arr1.length = ind1;
arr2.length = ind2;
// reverse and concat to array
arr = arr1.concat(arr2.reverse());
console.log(arr);
Clean, Fast and efficient.

Using es6
let arr1 = [1,2,3,4,5,6,7,8,9],
arr2 = [10,11,12,13,14,15];
let ind1 = 6,
ind2 = 3;
let newArr = [...arr1.slice(0, ind1), ...arr2.slice(0, ind2).reverse()];
console.log(newArr)

If you want to concat many arrays you can look at this solution. This lets you to concat how many arrays you want and in which order using function cascading. You can continue this cascading and use optional parameter for reverse order.
const arr1 = [1,2,3,4,5,6,7,8,9];
const arr2 = [10,11,12,13,14,15];
const obj = {
items: [],
concat(arr, index, isReverse = false) {
let temp = arr.slice(0, index);
this.items = this.items.concat(isReverse ? temp.reverse() : temp);
return this;
}
};
obj.concat(arr1, 6).concat(arr2, 3, true);
console.log(obj.items);

Related

How can i add new column to a 2D array in javascript after each iteration?

I have 2 arrays. (arr1, arr2) I want to take the value at index 0 and
multiply it by each value in arr2, and add each value to a new row in
a 2D array.
ex.
arr1 = [1,3,5,7] arr2 = [4,2,1,6]
Outcome should be:
2Darray = [
[4,12,20,28],
[2,6,10,14],
[1,3,5,7],
[6,18,30,42]
];
Im having trouble with the for loop in javascript and how to create a
new row after each iteration. ```
Thanks
Using map like others said would be best.
Using the remainder operator(%) makes the most sense in my head:
const arr1 = [1,3,5,7];
const arr2 = [4,2,1,6];
var twoDemArray = [];
for (var i = 0; i < arr1.length; i++) {
let tempArr = [];
for (var j = 1; j < arr2.length+1; j++) {
let newNum = arr1[i]*arr2[j-1];
tempArr.push(newNum);
if (j % arr2.length == 0) {
twoDemArray.push(tempArr);
tempArr = [];
};
};
};
console.log(twoDemArray)
//do stuff with twoDemArray
Mapping over both arrays helps.
arr1 = [1,3,5,7];
arr2 = [4,2,1,6];
let res = arr2.map(a2 => arr1.map(a1 => a1*a2))
console.log(res);
You could map the arrays with the product of the values.
const
array1 = [1, 3, 5, 7],
array2 = [4, 2, 1, 6],
result = array2.map(v => array1.map(w => v * w));
result.map(a => console.log(...a));
console.log(result);

Split an Array with specific chunks size

For example I have a chunks array, this array has the sizes of individual chunks.
let example = [3,3]; // Chunks array
let auxarrayindex = [1,2,3,4,5,6]; // Array that I want to splice
let example2 = [3,2,3]; // Chunks array
let auxarrayindex2 = [1,2,3,4,5,6,7,8]; // Array that I want to splice
The result that I want is:
[1,2,3],[4,5,6] and the second [1,2,3],[4,5],[6,7,8]
This is my code:
for (let auxexample = 0; auxexample < example.length; auxexample++) {
finalauxarray.push(auxarrayindex.slice(0, example[auxexample]));
}
The result from my code is:
[1,2,3],[1,2,3] and the second [1,2,3],[1,2],[1,2,3]
The problem is that your slice always starts at the same index (0).
Use a variable (like i) that you increase as you take chunks:
let example = [3,2,3];
let auxarrayindex = [1,2,3,4,5,6,7,8];
let finalauxarray = [];
let i = 0;
for (let auxexample = 0; auxexample < example.length; auxexample++) {
finalauxarray.push(auxarrayindex.slice(i, i+=example[auxexample]));
}
console.log(finalauxarray);
You could also use map for your loop:
let example = [3,2,3];
let auxarrayindex = [1,2,3,4,5,6,7,8];
let i = 0;
let finalauxarray = example.map(size => auxarrayindex.slice(i, i+=size));
console.log(finalauxarray);
The problem is because of the slice parameters are wrong
You can learn more about how slice works on this link
https://www.w3schools.com/jsref/jsref_slice_array.asp
It takes as first parameter the starti g position and as last parameter the ending position which is not included in the result
You can aslo use splice for this as well
https://www.w3schools.com/jsref/jsref_splice.asp
Hope that helps
Working example using splice instead of slice as I think it offers a slightly cleaner API for this particular use-case:
let example = [3, 3];
let auxArrayIndex = [1, 2, 3, 4, 5, 6];
let example2 = [3, 2, 3];
let auxArrayIndex2 = [1, 2, 3, 4, 5, 6, 7, 8];
function getChunks(chunkSizes, array) {
let result = [];
for (let chunkSize of chunkSizes) {
result.push(array.splice(0, chunkSize));
}
return result;
}
let chunks = getChunks(example, auxArrayIndex);
let chunks2 = getChunks(example2, auxArrayIndex2);
console.log(chunks); // logs "[1,2,3], [4,5,6]"
console.log(chunks2); // logs "[1,2,3], [4,5], [6,7,8]"

Combining two arrays with different number of elements

Let’s assume we have this two arrays:
x = [1, 2, 3];
y = ['a', 'b'];
What would be the best way to combine them and get the following result:
newArray = ['1a', '1b', '2a', '2b', '3a', '3b'];
Here is one way of doing that:
x.reduce(function(arr, x) {
return arr.concat(y.map(function(y) {
return x + y;
}));
}, []);
//=> ["1a", "1b", "2a", "2b", "3a", "3b"]
Try this:
var x = [1, 2, 3];
var y = ['a', 'b'];
var output = [];
for (var i = 0; i < x.length; i++) {
for (var j = 0; j < y.length; j++) {
output.push(x[i]+y[j]);
}
}
document.getElementById('output').innerHTML = JSON.stringify(output);
<div id="output"></div>
Try this..
var x = [1, 2, 3];
var y = ['a', 'b'];
var newarr = [];
for(var i=0;i<x.length;i++){
for(var j=0;j<y.length;j++){
newarr.push(x[i]+y[j]);
}
}
//alert(newarr);
DEMO
If arrow functions are supported you obtain the desired result like this:
[].concat.apply([],
x.map(x => y.map(y => x+y))
);
If not, you have to write it like this
[].concat.apply([],
x.map(function(x) { return y.map(function(y) {return x+y })})
);
Explanation:
The middle line yields the following result:
[ ["1a", "1b"], ["2a", "2b"], ["3a", "3b"] ]
Then the Array.prototype.concat method is used to concatenate the inner arrays.
You could simply create a array to be returned and do a simple loop for the array that contains numbers. Inside of that loop, you create another loop for the array of combinations to the numbers (var b=0,e=comb.length;e>b;b++). Using the i from the first loop (for(var i=0,l=array.length;l>i;i++)) you push the array at it (a[i]) with the array of combinations at the position b (c[b]) (inside of the loop that's inside of the first loop) to the new array. Finally, return the new array.
function CombineExample(a,c){
var New=[];
for(var i=0,l=a.length;l>i;i++){
for(var b=0,e=c.length;e>b;b++){
New.push(a[i]+c[b])
}
}
return New
}
Clean! And do this to use:
CombineExample([1,2,3],['a','b'])
/* returns ["1a", "1b", "2a", "2b", "3a", "3b"] */
Use nested loops to iterate all elements of the participating arrays. Populate new array elements inside the inner loop:
var x = [1, 2, 3];
var y = ['a', 'b'];
var newArray = [];
x.forEach(function(xItem) {
y.forEach(function(yItem) {
newArray.push(xItem.toString().concat(yItem));
});
});
console.log(newArray);
The simplest approach:
var x = ["a", "b", "c"];
var y = [1, 2, 3];
var newArray = [];
var i = 0;
for (;i < x.length;++i) {
var j = 0;
for (;j < y.length;++j) {
newArray.push(x[i] + y[j]);
}
}
;
Please do note that if both arrays are numeric, this will actually add the numbers, not concatenate. You'd need to do some string conversion.
var x = [1, 2, 3];
var y = ['a', 'b'];
var z = [];
for(var i=0;i<x.length;i++){
for(var j=0;j<y.length;j++){
z.push(x[i]+y[j]);
}
}
Are you seriously asking for that?

Sort Object Containing Multiple Arrays: JavaScript [duplicate]

for hours i've been trying to figure out how to sort 2 array dependently.
Let's say I have 2 arrays.
First one:
array1 = ['zzzzz', 'aaaaaa', 'ccccc'];
and the second one:
array2 = [3, 7, 1];
I sort the first one with array1.sort(); and it becomes [aaaaaa, cccccc, zzzzzz]
now what I want is that the second one becomes [7, 1, 3]
I think it's quite simple but i'm trying to implement this in something a little more complex, im new and i keep mixing up things.
Thanks
I would "zip" them into one array of objects, then sort that with a custom sort callback, then "unzip" them back into the two arrays you wanted:
var array1 = ['zzzzz', 'aaaaaa', 'ccccc'],
array2 = [3, 7, 1],
zipped = [],
i;
for(i=0; i<array1.length; ++i) {
zipped.push({
array1elem: array1[i],
array2elem: array2[i]
});
}
zipped.sort(function(left, right) {
var leftArray1elem = left.array1elem,
rightArray1elem = right.array1elem;
return leftArray1elem === rightArray1elem ? 0 : (leftArray1elem < rightArray1elem ? -1 : 1);
});
array1 = [];
array2 = [];
for(i=0; i<zipped.length; ++i) {
array1.push(zipped[i].array1elem);
array2.push(zipped[i].array2elem);
}
alert('Sorted arrays:\n\narray1: ' + array1 + '\n\narray2: ' + array2);
Here's a working fiddle.
Here's a simple function that will do the trick:
function sortTogether(array1, array2) {
var merged = [];
for(var i=0; i<array1.length; i++) { merged.push({'a1': array1[i], 'a2': array2[i]}); }
merged.sort(function(o1, o2) { return ((o1.a1 < o2.a1) ? -1 : ((o1.a1 == o2.a1) ? 0 : 1)); });
for(var i=0; i<merged.length; i++) { array1[i] = merged[i].a1; array2[i] = merged[i].a2; }
}
Usage demo (fiddle here):
var array1 = ['zzzzz', 'aaaaaa', 'ccccc'];
var array2 = [3, 7, 1];
console.log('Before..: ',array1,array2);
sortTogether(array1, array2); // simply call the function
console.log('After...: ',array1,array2);
Output:
Before..: ["zzzzz", "aaaaaa", "ccccc"] [3, 7, 1]
After...: ["aaaaaa", "ccccc", "zzzzz"] [7, 1, 3]
Instead of two arrays of primitive types (strings, numbers) you can make an array of objects where one property of the object is string (containing "aaaaa", "cccccc", "zzzzzz") and another is number (7,1,3). This way you will have one array only, which you can sort by any property and the other property will remain in sync.
It just so happens I had some old code lying around that might do the trick:
function arrVirtualSortGetIndices(array,fnCompare){
var index=array.map(function(e,i,a){return i;});
fnCompare=fnCompare || defaultStringCompare;
var idxCompare=function (aa,bb){return fnCompare(array[aa],array[bb]);};
index.sort(idxCompare);
return index;
function defaultStringCompare(aa,bb){
if(aa<bb)return -1;
if(bb<aa)return 1;
return 0;
}
function defaultNumericalCompare(aa,bb){
return aa-bb;
}
}
function arrReorderByIndices(array,indices){
return array.map(
function(el,ix,ar){
return ar[indices[ix]];
}
);
}
var array1 = ['zzzzz', 'aaaaaa', 'ccccc'];
var array2 = [3, 7, 1];
var indices=arrVirtualSortGetIndices(array1);
var array2sorted=arrReorderByIndices(array2,indices);
array2sorted;
/*
7,1,3
*/
Sorry, I don't do 'fors'. At least not when I don't have to.
And fiddle.
Also, an alternative fiddle that sorts the results when given an array of objects like this:
given:
var list = [
{str:'zzzzz',value:3},
{str:'aaaaa',value:7},
{str:'ccccc',value:1}
];
outputs:
[
{str: "aaaaa", value: 7},
{str: "ccccc", value: 1},
{str: "zzzzz", value: 3}
]
Assumption:
The arrays are the same length (this is implied by your question)
the contents can be compared with > and < (true in your example, but I wanted to make it clear that it was assumed here)
So then we can use an insertion sort.
var value,len = array1.length;
for (i=0; i < len; i++) {
value = array1[i];
for (j=i-1; j > -1 && array1[j] > value; j--) {
array1[j+1] = array1[j];
array2[j+1] = array2[j];
}
items[j+1] = value;
}
Using a solution found here to find the new indices after sorting an array, you can apply those indices to array2 like so.
function sortWithIndices(toSort) {
for (var i = 0; i < toSort.length; i++) {
toSort[i] = [toSort[i], i];
}
toSort.sort(function(left, right) {
return left[0] < right[0] ? -1 : 1;
});
toSort.sortIndices = [];
for (var j = 0; j < toSort.length; j++) {
toSort.sortIndices.push(toSort[j][2]);
toSort[j] = toSort[j][0];
}
return toSort;
}
var array1 = ['zzzz', 'aaaa', 'cccc'];
var array2 = [3, 7, 1];
// calculate the indices of array1 after sorting. (attached to array1.sortIndices)
sortWithIndices(array1);
// the final array after applying the sorted indices from array1 to array2
var final = [];
// apply sorted indices to array2
for(var i = 0; i < array1.sortIndices.length; i++)
final[i] = array2[array1.sortIndices[i]];
// output results
alert(final.join(","));
JSFiddle Demo

How can I reverse an array in JavaScript without using libraries?

I am saving some data in order using arrays, and I want to add a function that the user can reverse the list. I can't think of any possible method, so if anybody knows how, please help.
Javascript has a reverse() method that you can call in an array
var a = [3,5,7,8];
a.reverse(); // 8 7 5 3
Not sure if that's what you mean by 'libraries you can't use', I'm guessing something to do with practice. If that's the case, you can implement your own version of .reverse()
function reverseArr(input) {
var ret = new Array;
for(var i = input.length-1; i >= 0; i--) {
ret.push(input[i]);
}
return ret;
}
var a = [3,5,7,8]
var b = reverseArr(a);
Do note that the built-in .reverse() method operates on the original array, thus you don't need to reassign a.
Array.prototype.reverse() is all you need to do this work. See compatibility table.
var myArray = [20, 40, 80, 100];
var revMyArr = [].concat(myArray).reverse();
console.log(revMyArr);
// [100, 80, 40, 20]
Heres a functional way to do it.
const array = [1,2,3,4,5,6,"taco"];
function reverse(array){
return array.map((item,idx) => array[array.length-1-idx])
}
20 bytes
let reverse=a=>[...a].map(a.pop,a)
const original = [1, 2, 3, 4];
const reversed = [...original].reverse(); // 4 3 2 1
Concise and leaves the original unchanged.
reveresed = [...array].reverse()
The shortest reverse method I've seen is this one:
let reverse = a=>a.sort(a=>1)
**
Shortest reverse array method without using reverse method:
**
var a = [0, 1, 4, 1, 3, 9, 3, 7, 8544, 4, 2, 1, 2, 3];
a.map(a.pop,[...a]);
// returns [3, 2, 1, 2, 4, 8544, 7, 3, 9, 3, 1, 4, 1, 0]
a.pop method takes an last element off and puts upfront with spread operator ()
MDN links for reference:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop
two ways:
counter loop
function reverseArray(a) {
var rA = []
for (var i = a.length; i > 0; i--) {
rA.push(a[i - 1])
}
return rA;
}
Using .reverse()
function reverseArray(a) {
return a.reverse()
}
This is what you want:
array.reverse();
DEMO
Here is a version which does not require temp array.
function inplaceReverse(arr) {
var i = 0;
while (i < arr.length - 1) {
arr.splice(i, 0, arr.pop());
i++;
}
return arr;
}
// Useage:
var arr = [1, 2, 3];
console.log(inplaceReverse(arr)); // [3, 2, 1]
I've made some test of solutions that not only reverse array but also makes its copy. Here is test code. The reverse2 method is the fastest one in Chrome but in Firefox the reverse method is the fastest.
var array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
var reverse1 = function() {
var reversed = array.slice().reverse();
};
var reverse2 = function() {
var reversed = [];
for (var i = array.length - 1; i >= 0; i--) {
reversed.push(array[i]);
}
};
var reverse3 = function() {
var reversed = [];
array.forEach(function(v) {
reversed.unshift(v);
});
};
console.time('reverse1');
for (var x = 0; x < 1000000; x++) {
reverse1();
}
console.timeEnd('reverse1'); // Around 184ms on my computer in Chrome
console.time('reverse2');
for (var x = 0; x < 1000000; x++) {
reverse2();
}
console.timeEnd('reverse2'); // Around 78ms on my computer in Chrome
console.time('reverse3');
for (var x = 0; x < 1000000; x++) {
reverse3();
}
console.timeEnd('reverse3'); // Around 1114ms on my computer in Chrome
53 bytes
function reverse(a){
for(i=0,j=a.length-1;i<j;)a[i]=a[j]+(a[j--]=a[i++],0)
}
Just for fun, here's an alternative implementation that is faster than the native .reverse method.
You can do
var yourArray = ["first", "second", "third", "...", "etc"]
var reverseArray = yourArray.slice().reverse()
console.log(reverseArray)
You will get
["etc", "...", "third", "second", "first"]
> var arr = [1,2,3,4,5,6];
> arr.reverse();
[6, 5, 4, 3, 2, 1]
array.reverse()
Above will reverse your array but modifying the original.
If you don't want to modify the original array then you can do this:
var arrayOne = [1,2,3,4,5];
var reverse = function(array){
var arrayOne = array
var array2 = [];
for (var i = arrayOne.length-1; i >= 0; i--){
array2.push(arrayOne[i])
}
return array2
}
reverse(arrayOne)
function reverseArray(arr) {
let reversed = [];
for (i = 0; i < arr.length; i++) {
reversed.push((arr[arr.length-1-i]))
}
return reversed;
}
Using .pop() method and while loop.
var original = [1,2,3,4];
var reverse = [];
while(original.length){
reverse.push(original.pop());
}
Output: [4,3,2,1]
I'm not sure what is meant by libraries, but here are the best ways I can think of:
// return a new array with .map()
const ReverseArray1 = (array) => {
let len = array.length - 1;
return array.map(() => array[len--]);
}
console.log(ReverseArray1([1,2,3,4,5])) //[5,4,3,2,1]
// initialize and return a new array
const ReverseArray2 = (array) => {
const newArray = [];
let len = array.length;
while (len--) {
newArray.push(array[len]);
}
return newArray;
}
console.log(ReverseArray2([1,2,3,4,5]))//[5,4,3,2,1]
// use swapping and return original array
const ReverseArray3 = (array) => {
let i = 0;
let j = array.length - 1;
while (i < j) {
const swap = array[i];
array[i++] = array[j];
array[j--] = swap;
}
return array;
}
console.log(ReverseArray3([1,2,3,4,5]))//[5,4,3,2,1]
// use .pop() and .length
const ReverseArray4 = (array) => {
const newArray = [];
while (array.length) {
newArray.push(array.pop());
}
return newArray;
}
console.log(ReverseArray4([1,2,3,4,5]))//[5,4,3,2,1]
As others mentioned, you can use .reverse() on the array object.
However if you care about preserving the original object, you may use reduce instead:
const original = ['a', 'b', 'c'];
const reversed = original.reduce( (a, b) => [b].concat(a) );
// ^
// |
// +-- prepend b to previous accumulation
// original: ['a', 'b', 'c'];
// reversed: ['c', 'b', 'a'];
Pure functions to reverse an array using functional programming:
var a = [3,5,7,8];
// ES2015
function immutableReverse(arr) {
return [ ...a ].reverse();
}
// ES5
function immutableReverse(arr) {
return a.concat().reverse()
}
It can also be achieved using map method.
[1, 2, 3].map((value, index, arr) => arr[arr.length - index - 1])); // [3, 2, 1]
Or using reduce (little longer approach)
[1, 2, 3].reduce((acc, curr, index, arr) => {
acc[arr.length - index - 1] = curr;
return acc;
}, []);
reverse in place with variable swapping (mutative)
const myArr = ["a", "b", "c", "d"];
for (let i = 0; i < (myArr.length - 1) / 2; i++) {
const lastIndex = myArr.length - 1 - i;
[myArr[i], myArr[lastIndex]] = [myArr[lastIndex], myArr[i]]
}
Reverse by using the sort method
This is a much more succinct method.
const resultN = document.querySelector('.resultN');
const resultL = document.querySelector('.resultL');
const dataNum = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
const dataLetters = ['a', 'b', 'c', 'd', 'e'];
const revBySort = (array) => array.sort((a, b) => a < b);
resultN.innerHTML = revBySort(dataNum);
resultL.innerHTML = revBySort(dataLetters);
<div class="resultN"></div>
<div class="resultL"></div>
Using ES6 rest operator and arrow function.
const reverse = ([x, ...s]) => x ? [...reverse(s), x] : [];
reverse([1,2,3,4,5]) //[5, 4, 3, 2, 1]
Use swapping and return the original array.
const reverseString = (s) => {
let start = 0, end = s.length - 1;
while (start < end) {
[s[start], s[end]] = [s[end], s[start]]; // swap
start++, end--;
}
return s;
};
console.log(reverseString(["s", "t", "r", "e", "s", "s", "e", "d"]));
Infact the reverse() may not work in some cases, so you have to make an affectation first as the following
let a = [1, 2, 3, 4];
console.log(a); // [1,2,3,4]
a = a.reverse();
console.log(a); // [4,3,2,1]
or use concat
let a = [1, 2, 3, 4];
console.log(a, a.concat([]).reverse()); // [1,2,3,4], [4,3,2,1]
What about without using push() !
Solution using XOR !
var myARray = [1,2,3,4,5,6,7,8];
function rver(x){
var l = x.length;
for(var i=0; i<Math.floor(l/2); i++){
var a = x[i];
var b = x[l-1-i];
a = a^b;
b = b^a;
a = a^b;
x[i] = a;
x[l-1-i] = b;
}
return x;
}
console.log(rver(myARray));
JavaScript already has reverse() method on Array, so you don't need to do that much!
Imagine you have the array below:
var arr = [1, 2, 3, 4, 5];
Now simply just do this:
arr.reverse();
and you get this as the result:
[5, 4, 3, 2, 1];
But this basically change the original array, you can write a function and use it to return a new array instead, something like this:
function reverse(arr) {
var i = arr.length, reversed = [];
while(i) {
i--;
reversed.push(arr[i]);
}
return reversed;
}
Or simply chaning JavaScript built-in methods for Array like this:
function reverse(arr) {
return arr.slice().reverse();
}
and you can call it like this:
reverse(arr); //return [5, 4, 3, 2, 1];
Just as mentioned, the main difference is in the second way, you don't touch the original array...
How about this?:
function reverse(arr) {
function doReverse(a, left, right) {
if (left >= right) {
return a;
}
const temp = a[left];
a[left] = a[right];
a[right] = temp;
left++;
right--;
return doReverse(a, left, right);
}
return doReverse(arr, 0, arr.length - 1);
}
console.log(reverse([1,2,3,4]));
https://jsfiddle.net/ygpnt593/8/

Categories

Resources