How to create nested array of different length from a multidimensional array - javascript

I have an array that looks like this:
arr = [[1,2,3],
[4,5,6],
[7,8,9]]
I have initialized an empty array and I want put the diagonals of the arr inside the new array. So i've tried this:
arr = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
new_arr = [];
tail = arr.length - 1;
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr[i].length; j++) {
if (j == i) {
new_arr.push(arr[i][j]);
}
if (j == tail) {
new_arr.push(arr[i][j]);
tail--;
}
}
}
console.log(new_arr)
The logic seems to work but I can't seem to get the structure right. What I want is to nest two arrays inside the new array like this:
[[1,5,9],[3,5,7]]
But what I get is one array with the right values unordered. How to get the expected output? Any help is appreciated. Thanks!

You need to have 2 separate temporary arrays. And you don't need nested loops. You can optimize the code like this with a single loop if you understand the math.
arr = [[1,2,3],
[4,5,6],
[7,8,9]];
function findDiagonals(arr) {
const diagonal_1 = [];
const diagonal_2 = [];
for( let i = 0; i < arr.length; i++ ) {
diagonal_1.push(arr[i][i]);
diagonal_2.push(arr[i][arr.length - (i+1)]);
}
return [diagonal_1, diagonal_2];
}
console.log(findDiagonals(arr));

var arr = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
var diagonal1 = [];
var diagonal2 = [];
for (var i = 0; i < arr.length; i++) {
diagonal1.push(arr[i][i]);
diagonal2.push(arr[i][arr.length - i - 1]);
}
var new_arr = [diagonal1, diagonal2];
console.log(new_arr)

The following solution would work for you if the width and height of the number matrix is always equal.
const arr = [[1,2,3],
[4,5,6],
[7,8,9]];
const result = [[],[]];
arr.map((row,index) => {
result[0].push(row[0+index]);
result[1].push(row[row.length - index - 1]);
});
console.log(result); // [[1,5,9],[3,5,7]]

This is a O(n) approach by using the function Array.prototype.reduce.
const arr = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
const result = arr.reduce(([left, right], array, row, {length}) => {
return [[...left, array[row]], [...right, array[length - row - 1]]];
}, [[],[]]);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

the difficulty is low:
const
arr = [[1,2,3],[4,5,6],[7,8,9]]
, new_arr = [[],[]]
;
let p0 = 0, p1 = arr.length
for( let inArr of arr)
{
new_arr[0].push( inArr[p0++] )
new_arr[1].push( inArr[--p1] )
}
console.log( JSON.stringify( new_arr ))
in a one Line code:
const
arr = [[1,2,3],[4,5,6],[7,8,9]]
, new_arr = arr.reduce(([lft,rgt],A,i,{length:Sz})=>([[...lft,A[i]],[...rgt,A[Sz-i-1]]]),[[],[]])
;
console.log( JSON.stringify( new_arr )) // [[1,5,9],[3,5,7]]

Related

How to get all substrings (contiguous subsequences) of my JavaScript array?

My task is to split the given array into smaller arrays using JavaScript. For example [1, 2, 3, 4] should be split to [1] [1, 2] [1, 2, 3] [1, 2, 3, 4] [2] [2, 3] [2, 3, 4] [3] [3, 4] [4].
I am using this code:
let arr = [1, 2, 3, 4];
for (let i = 1; i <= arr.length; i++) {
let a = [];
for (let j = 0; j < arr.length; j++) {
a.push(arr[j]);
if (a.length === i) {
break;
}
}
console.log(a);
}
And I get the following result: [1] [1, 2] [1, 2, 3] [1, 2, 3, 4] undefined
What am I missing/doing wrong?
For the inner array, you could just start with the index of the outer array.
var array = [1, 2, 3, 4],
i, j, l = array.length,
result = [];
for (i = 0; i < l; i++) {
for (j = i; j < l; j++) {
result.push(array.slice(i, j + 1));
}
}
console.log(result.map(a => a.join(' ')));
.as-console-wrapper { max-height: 100% !important; top: 0; }
You have two issues in your code:
You need to have loop to initialize with the value of i for the inner loop so that it consider the next index for new iteration of i
You need to remove that break on the length which you have in inner loop.
let arr = [1, 2, 3, 4];
for (let i = 0; i <= arr.length; i++) {
let a = [];
for (let j = i; j < arr.length; j++) {
a.push(arr[j]);
console.log(a);
}
}
Try this
let arr = [1, 2, 3, 4];
for (let i = 0; i <= arr.length; i++) {
let a = [];
for (let j = i; j < arr.length; j++) {
a.push(arr[j]);
console.log(a);
}
}
If you don't want to mutate your array.
let arr = [1, 2, 3, 4];
let res = [];
for (let i = 0; i <= arr.length; i++) {
let a = [];
for (let j = i; j < arr.length; j++) {
a = [...a, arr[j]];
res = [...res, a];
}
}
console.log(res);
i have prepare stackblitz for this case.
let source = [1,2,3,4];
const output = [];
const arrayMultiplier = (source) => {
const eachValueArray = [];
source.forEach((item, index) => {
// Will push new array who will be sliced source array.
eachValueArray.push(source.slice(0, source.length - index));
});
//We reverse array to have right order.
return eachValueArray.reverse();
};
for(let i = 0; i <= source.length; i++) {
output.push(...arrayMultiplier(source));
source.shift(); // Will recraft source array by removing first index.
}
//Don't forget last item.
output.push(source);
console.log(output);
Is not the most shorten solution but do the job
== update after code review ==
// [...]
const arrayMultiplier = (source) => {
// Will push new array who will be sliced source array.
// We reverse array to have right order.
return source.map((item, index) => source.slice(0, source.length - index)).reverse();
};
// [...]
Use two iteration
get slice array based on loop index.
use sliced array and combine array element.
var arr = [1, 2, 3, 4];
let newArra =[];
arr.map((x,i)=> {
let remainArr = arr.slice(i);
return remainArr.forEach((y, r) => newArra.push(remainArr.slice(0, r+1)))
})
newArra.forEach(x=> console.log(x))

Arrays withing an array: how to push all elements forward by one with javascript

This is my array of arrays:
arr_1 = [1,2,3]
arr_2 = [4,5,6]
arr_3 = [7,8,9]
arr = [arr_1, arr_2, arr_3]
arr = [[1,2,3], [4,5,6], [7,8,9]]
What I want to do is push all elements like so that the final array is like the following and insert another element at the beginning of my array:
arr = [[i,1,2], [3,4,5], [6,7,8], [9]]
All sub-arrays must not be more than 3 elements.
Thanks for your help.
You could visit all inner arrays and unshift the leftover values from the previous loop.
var array = [[1, 2, 3], [4, 5, 6], [7, 8, 9]],
chunk = 3,
item = 'x',
i = 0,
temp = [item];
while (i < array.length) {
array[i].unshift(...temp);
temp = array[i].splice(chunk, array[i].length - chunk);
i++;
}
if (temp.length) {
array.push(temp);
}
console.log(array.map(a => a.join(' ')));
You can use the function reduce
var arr = [[1,2,3], [4,5,6], [7,8,9]],
newElem = "newOne",
all = [newElem, ...arr.reduce((a, c) => [...a, ...c], [])], // All together
// Build the desired output asking for the result of:
// element mod 3 === 0
result = all.reduce((a, c, i) => {
if (i % 3 === 0) a.push([c]);
else a[a.length - 1].push(c);
return a;
}, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You could move on each iteration last element from previous array to next one and if the last sub-array has more then 3 elements then remove the last one and add it to new array.
let arr_1 = [1, 2, 3],
arr_2 = [4, 5, 6],
arr_3 = [7, 8, 9],
arr = [arr_1, arr_2, arr_3]
setInterval(function() {
const last = arr.length - 1;
const newElement = parseInt(Math.random() * 30)
arr.forEach((a, i) => {
if(i == 0) a.unshift(newElement);
if(arr[i + 1]) arr[i + 1].unshift(a.pop())
else if(arr[last].length > 3) arr[last + 1] = [arr[last].pop()]
})
console.log(JSON.stringify(arr))
}, 1000)
You can do this quite succinctly with a simple unravel/ravel. It easy to adjust group size too.
let arr = [ [1,2,3], [4,5,6], [7,8,9]]
let newEl = 0
let groupSize = 3
var newArr = [];
var unravelled = arr.reduce((a, c) => a.concat(c), [newEl])
while(unravelled.length) newArr.push(unravelled.splice(0,groupSize));
console.log(newArr)
arr_1 = [1, 2, 3]
arr_2 = [4, 5, 6]
arr_3 = [7, 8, 9]
arr = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
function reassignChunk(x) {
// create an array which will be used to store unwrapped values
var newArray = [];
arr.forEach(function(elem) {
newArray.push(...elem); //using spread operator to unwrap values
});
newArray.unshift(x, limit)
var modArray = [];
var m, j, temparray, chunk = 3;
for (m = 0; m < newArray.length; m = m + limit) {
// creatinging new array using slice
modArray.push(newArray.slice(m, m + limit));
}
console.log(modArray)
}
reassignChunk(13, 3)
arr = [[i,1,2], [3,4,5], [6,7,8], [9]]
Assuming all your elements are numbers, you can do it like this:
Prepend i to the array
Flatten the array
Convert the array to a comma-separated string
Split the string into chunks of at most 3 numeric substrings (2 commas)
Convert the chunks back into arrays of numbers
const arr_1 = [1,2,3];
const arr_2 = [4,5,6];
const arr_3 = [7,8,9];
const i = 42;
const result = [i,...arr_1,...arr_2,...arr_3].join()
.match(/(?:[^,]+(,|$)){1,2}[^,]*/g).map( x => x.split(',').map(Number) )
;
console.log( result );
You may do your 2d unshifting simply as follows;
var arr_1 = [1,2,3],
arr_2 = [4,5,6],
arr_3 = [7,8,9],
arr = [arr_1, arr_2, arr_3],
us2d = (a2d,...is) => is.concat(...a2d)
.reduce((r,e,i) => (i%3 ? r[r.length-1].push(e)
: r.push([e]), r), []);
console.log(JSON.stringify(us2d(arr,0)));
console.log(JSON.stringify(us2d(arr,-2,-1,0)));

Merge two of one dimensional array into two dimensional array javascript

I have n (but for now, let say just two) of one dimensional arrays like this image of my console :
And I want to merge these two arrays by the corresponding key and put it into two dimensional array :
The result is something like :
[["1 279 226,08" , "127"],[null , null],["-188 033,77", "154"],..... so on ......]
And the list of one dimensional array is dynamic, it could be more than 2 arrays.
So example if I have 3 arrays, then my two dimensional array would look like :
[ ["1 279 226,08" , "127" , "blabla"], [null , null , "blabla"], ["-188 033,77", "154", "blabla"], ..... so on ......]
Any ideas of implementing it would be appreciate.
You could transpose the array with a nested loop and switch the indices for assigning the values.
var array = [["1 279 226,08", null, "-188 033,77"], ["127", null, "154"], ["blabla", "blabla", "blabla"]],
result = array.reduce(function (r, a, i) {
a.forEach(function (b, j) {
r[j] = r[j] || [];
r[j][i] = b;
});
return r;
}, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Since all of your arrays have the same size, you can loop just on the lenght of the first array, i.e. a.
Then we pass to appendArrays the single value of a , b, ..., and we return the an array to push into merged
var a = ["123", null, "ciao"]
var b = ["321", 1, "pippo"]
var c = ["111", 5, "co"]
var merged = []
for (i = 0; i < a.length; i++) {
merged.push(appendArrays(a[i], b[i], c[i]));
}
console.log(merged);
function appendArrays() {
var temp = []
for (var i = 0; i < arguments.length; i++) {
temp.push(arguments[i]);
}
return temp;
}
This should do what you want.
var arr1 = [1, 2, 3, 4, 5, 6];
var arr2 = [6, 5, 4, 3, 2, 1];
var arr3 = [7, 8, 9, 10, 11, 5];
var arr4 = [12, 34, 55, 77, 22, 426];
var arrCollection = [arr1, arr2, arr3, arr4];
// if array sizes are variable.
// if not max = arrCollection[0].length will do
var max = Math.max.apply(Math, arrCollection.map(function(a) {
return a.length;
}));
var arrFinal = [];
for (let i = 0; i < max; i++) {
var arr = [];
arrCollection.forEach(function(a) {
arr.push(a[i]);
});
arrFinal.push(arr);
}
console.log(arrFinal);
You can create this with two forEach() loops.
var arr1 = [[1, 2], [3, 4], [5, 6]];
var arr2 = [[1, 2, 3], [4, 5, 6], [7, 8], [9, 10, 12, 14]];
let merge = function(arr) {
var result = [];
arr.forEach(function(e, i) {
e.forEach(function(a, j) {
if (!result[j]) result[j] = [a];
else result[j].push(a)
})
});
return result;
}
console.log(JSON.stringify(merge(arr1)))
console.log(JSON.stringify(merge(arr2)))

Javascript- Two array intersecton by same key

I would appreciate if the following could be solved
Arrays
var arr1 = [1,2,3,4,5];
var arr2 = [0,2,1,3];
var arr3 = [];
arr3 = arr1 (intersection) arr2;
Output must be shown below
arr3 = [2];
Javascript button value how to add an array?
<?php for ($i=1; $i <= 7 ; $i++) { ?> <td> <input type="button" id="myButton1" value="0" onClick="javascript:change(this);"></input> </td> <?php } ?>
and then click the button, Clicking button of array index of value is change 0 to 1.
If I understand the requirements correctly, this should do the trick:
function matchingElements(arr1, arr2) {
var result = [];
for (var i = 0; i < arr1.length && i < arr2.length; i++) {
if (arr1[i] === arr2[i]) {
result.push(arr1[i]);
}
}
return result;
}
var arr1 = [1, 2, 3, 4, 5];
var arr2 = [0, 2, 1, 2];
var arr3 = matchingElements(arr1, arr2);
console.log(arr3);
// Output:
// [ 2 ]
Try it :
<html>
<head></head>
<body>
<script>
var arr1 = [1,2,3,4,5];
var arr2 = [0,2,3,3];
var arr3 = [];
function intersection(arr1,arr2){
len = arr1.length < arr2.length ? arr1.length : arr2.length;
for(var i=0 ; i<len; i++)
if(arr1[i]==arr2[i]){
arr3[0] = arr1[i];
break;
}
if(arr3.length > 0)
alert("intersection is : " + arr3[0]);
else
alert("No intersection");
}
intersection(arr1,arr2);
</script>
</body>
</html>
Based on the comments on the original question, I think it's possible that #KoPhyoHtet is actually trying to compute the Jaccard index of two sets. In that case, the following code should help. (It has a dependency on lodash.)
function jaccard(arr1, arr2) {
return _.intersection(arr1, arr2).length / _.union(arr1, arr2).length;
}
var arr1 = [1, 2, 3, 4, 5];
var arr2 = [0, 2, 1, 3];
// intersection is [1, 2, 3] (length 3)
// union is [0, 1, 2, 3, 4, 5] (length 6)
// Jaccard index should be 3/6 = 0.5
console.log(jaccard(arr1, arr2));
// Output:
// 0.5
this is the shortest version
const arr1 = [1,2,3,4,5]
const arr2 = [0,2,1,3]
const arr3 = arr1.filter(item => arr2.indexOf(item) > -1)

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