reverseArrayInPlace eloquentJS - javascript

I figured out a simple way to solve this, and it worked out.
var reverseArrayInPlace = function(arr) {
var result = [];
for(var i = 0; i < arr.length; i++) {
result.unshift(arr[i]);
}
for(var j = 0; j < result.length; j ++) {
arr[j] = result[j];
}
};
//test
var arrayValue = [1, 2, 3, 4, 5];
reverseArrayInPlace(arrayValue);
console.log(arrayValue);
//[5,4,3,2,1]
However, i'm wonder why can't I use an even simpler way by just assign the arr argument to the result value which is [5,4,3,2,1]? But the code below doesn't work, it still prints out [1,2,3,4,5].
var reverseArrayInPlace = function(arr) {
var result = [];
for(var i = 0; i < arr.length; i++) {
result.unshift(arr[i]);
}
arr = result;
};
//test
var arrayValue = [1, 2, 3, 4, 5];
reverseArrayInPlace(arrayValue);
console.log(arrayValue);
//[1,2,3,4,5]

Try this in your dev console:
var arr = [1,2,3];
function retArr(arr){
var res = arr;
res = [3,2,1];
return res;
}
retArr(arr); // returns 3,2,1
console.log(arr); // logs 1,2,3
All you did was create a new array!
Parameters of functions are pass-by-value.
the reason direct for-loop access works is because array properties are pass-by-reference.
P.S. an actual in-place reversal would look like this:
function reverseInPlace(array){
var swap = function(i,j){
var t = array[i];
array[i] = array[j];
array[j] = t;
};
for (var i = 0; i < array.length/2;i++){
swap(i,array.length-i-1);
}
}

Try using .slice(), .pop()
var reverseArrayInPlace = function(arr) {
var copy = arr.slice(0);
for (var n = 0; n < arr.length; n++) {
arr[n] = copy.pop();
}
return arr
};
//test
var arrayValue = [1, 2, 3, 4, 5];
reverseArrayInPlace(arrayValue);
console.log(arrayValue);
Alternatively, using Array.prototype.sort()
var reverseArrayInPlace = function(arr) {
arr.sort(function(a, b, index) {
return index < index + 1 ? -1 : 1
});
};
//test
var arrayValue = ["a", "b", "c", "d", "e"];
reverseArrayInPlace(arrayValue);
console.log(arrayValue);

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

What is the difference between [4,null,6] and [4,6]

Here is the question:
Compare two arrays and return a new array with any items only found in one of the two given arrays, but not both. In other words, return the symmetric difference of the two arrays.
And here is my code:
function diffArray(arr1, arr2) {
var newArr = [];
// Same, same; but different.
for (i = 0; i < arr1.length; i++) {
for (j = 0; j < arr2.length; j++)
while (arr1[i] === arr2[j])
delete arr2[j];
newArr = arr2;
}
return newArr;
}
console.log(diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]));
Please, tell me my mistakes.
If you work using indices as references which you delete, you'll leave those indices undefined.
You have to use push to add an item and splice to remove one.
The time complexity of the following code should be: O(nm) where n and m are the lengths of the arr1 and arr2 arrays respectively.
function diffArray(arr1, arr2) {
var newArr = [];
for (i = 0; i < arr1.length; i++) {
for (j = 0; j < arr2.length; j++)
while (arr1[i] === arr2[j])
arr2.splice(j, 1);
newArr = arr2;
}
return newArr;
}
console.log(diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]));
This should work, but I've found a different way that is a bit slower for short arrays but much faster for longer array.
The time complexity of the following code should be: O(3(n + m)), which is reduced to O(n + m) where n and m are the lengths of the arr1 and arr2 arrays respectively.
Look at this fiddle.
Here's it:
function diffArray(arr1, arr2) {
let obj1 = {}, obj2 = {};
for (let l = arr1.length, i = 0; i < l; i++)
obj1[arr1[i]] = undefined;
for (let l = arr2.length, i = 0; i < l; i++)
obj2[arr2[i]] = undefined;
let a = [];
for (let arr = arr1.concat(arr2), l = arr.length, i = 0, item = arr[0]; i < l; i++, item = arr[i])
if (item in obj1 !== item in obj2)
a.push(item);
return a;
}
console.log(diffArray([1, 2, 3, 5], [1, 2, 3, 4, 5]));
The task you are trying to complete asks you to create a new array, but instead you modify arr2. It would probably be easiest to just copy all elements not included in the other array to a new array, like this:
function diffArray(arr1, arr2) {
var newArray = [];
arr1.forEach(function(el) {
if (!arr2.includes(el)) {
newArray.push(el);
}
});
arr2.forEach(function(el) {
if (!arr1.includes(el)) {
newArray.push(el);
}
});
return newArray;
}
If you would rather try and fix your code instead, I can try to have another look at it.
I've used Array.prototype.filter method:
function diffArray(arr1, arr2) {
var dif01 = arr1.filter(function (t) {
return arr2.indexOf(t) === -1;
});
var dif02 = arr2.filter(function (t) {
return arr1.indexOf(t) === -1;
});
return (dif01).concat(dif02);
}
alert(diffArray([1, 2, 3, 6, 5], [1, 2, 3, 4, 7, 5]));
If you still want to use your code and delete the common elements, try to use Array.prototype.splice method instead of delete: the latter deletes the value, but keeps the index empty, while Array.prototype.splice will remove those whole indices within the given range and will reindex the items next to the range.
You can use Array.prototype.filter:
var array1 = [1, 2, 3, 5];
var array2 = [1, 2, 3, 4, 5];
var filteredArray = filter(array1, array2).concat(filter(array2, array1));
function filter(arr1, arr2) {
return arr1.filter(function(el) { return arr2.indexOf(el) < 0; });
}
Here is a working JSFiddle.
Try this:
function diffArray(arr1, arr2) {
var ret = [];
function checkElem(arrFrom, arrIn) {
for (var i = 0; i < arrFrom.length; ++i) {
var elem = arrFrom[i];
if (arrIn.indexOf(elem) === -1)
ret.push(elem);
}
}
checkElem(arr1, arr2);
checkElem(arr2, arr1);
return ret;
}
I hope this can solve your problem.

How do I sum up 2 dimensional array, ex index 0+index0

I encountered a problem!
for example! here is my 2 dimensional array: var array=[[1,2,3,4],[2,3,4,5],[3,4,5,6]];
and my desired outcome is : [[1,2,3,4],[2,3,4,5],[3,4,5,6],[6,9,12,15]]
the [6,9,12,15] came from adding the same index numbers of the previous inner arrays. (ex 1+2+3, 2+3+4, 3+4+5, 4+5+6 more clear : index 1 + index 1+ index1 produces 9)
I am so confused so far, the closes i did was to sum up [1,2,3,4][2,3,4,5][3,4,5,6], but I cant seem to do something with each and individual numbers :(
The question requested me to do nested for loops, So i cant use any thing like reduce, map, flatten, etc...
try with this way:https://jsfiddle.net/0L0h7cat/
var array=[[1,2,3,4],[2,3,4,5],[3,4,5,6]];
var array4 = [];
for (j = 0; j < array[0].length; j++) {
var num =0;
for(i=0;i< array.length;i++){
num += array[i][j];
}
array4.push(num);
}
array.push(array4);
alert(array);
Just iterate over the outer array and the inner arrays and add the values to the result array array[3].
var array = [[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6]];
array.forEach(function (a) {
a.forEach(function (b, i) {
array[3] = array[3] || [];
array[3][i] = (array[3][i] || 0) + b;
});
});
document.write('<pre>' + JSON.stringify(array, 0, 4) + '</pre>');
https://jsfiddle.net/0L0h7cat/
var array = [
[1, 2, 3, 4],
[2, 3, 4, 5],
[3, 4, 5, 6]
];
var sumArr = [];
for (var i = 0; i < array[0].length; i++) {
sumArr[i] = 0;
for (var j = 0; j < array.length; j++)
sumArr[i] += array[j][i];
}
array.push(sumArr);
If you are interested in Arrow Functions, this will work:-
var array = [[1, 2, 3, 4],[2, 3, 4, 5],[3, 4, 5, 6]];
var count = [];
array.forEach(x => x.forEach((y, i) => count[i] = (count[i] || 0) + y));
array.push(count);
console.log(array);
NOTE: Not cross browser support yet.
This is how -
var array=[[1,2,3,4],[2,3,4,5],[3,4,5,6]];
var array2=[]
for (var i = array[0].length;i--;) {
var sum=0;
for (var j = array.length; j--;) {
sum=sum+array[j][i];
}
array2.push(sum)
}
array.push(array2.reverse());
document.write('<pre>'+JSON.stringify(array) + '</pre>');
But I'm sure there are more elegant methods. I'm just learning by answering questions myself.
A simplistic approach with just conventional for loops
var input = [[1,2,3,4],[2,3,4,5],[3,4,5,6]];
function getSumOfArrayOfArrays(inputArray) {
var length = inputArray.length;
var result = [];
for(var i=0; i<length; i++){
for(var j=0; j<=3; j++){
result[j] = result[j] ? result[j] + inputArray[i][j] : inputArray[i][j];
}
}
return result;
}
var output = getSumOfArrayOfArrays(input); // [6,9,12,15]
var desiredOutput = input;
desiredOutput.push(output)
document.write(JSON.stringify(desiredOutput));
// [[1,2,3,4],[2,3,4,5],[3,4,5,6],[6,9,12,15]]
I try to avoid writing nested for loops.
var arrayOfArrays=[
[1,2,3,4],
[2,3,4,5],
[3,4,5,6]
];
//define a function to extend the Array prototype
Array.prototype.add = function(otherArray){
var result = [];
for(var i = 0; i < this.length; i++) {
result.push( this[i] + otherArray[i] )
}
return result;
};
//reduce array of arrays to get the result array `sum`
var sum = arrayOfArrays.reduce(function(arrayA, arrayB){
//`arrayA`+`arrayB` becomes another `arrayA`
return arrayA.add(arrayB)
});
//put `sum` back to `arrayOfArrays`
arrayOfArrays.push(sum);
document.write('<pre>' + JSON.stringify(arrayOfArrays) + '</pre>');

How to get common value from 4 different array with javascript

I have below arrow and I want to get common value from all four array. I have try below code and it's working but not the correct way I want. Instead of coming [2, 3] in new array it showing other value which are common at least in two or three array.
Fiddle Demo
My Code
var a = [11, 2, 3, 4],
b = [2, 6, 3, 5],
c = [4, 2, 20, 3],
d = [34, 2, 21, 5, 3],
result = [],
common = [];
function findCommon () {
for(var i = 0; i < arguments.length; i++){
var garr = arguments[i];
result = result.concat(arguments[i]);
};
}
findCommon(a,b,c,d);
var sorted_arr = result.sort();
for(var i = 0; i< result.length-1; i++){
if(result[i+1] == sorted_arr[i]){
common.push(result[i]);
}
};
alert(common); //[2, 2, 2, 3, 3, 4, 5]
You could use arrays as the values of an object, and use the numbers as the keys. It makes it easy to count the numbers then. Note, this code is also future proof, so that if you want fewer or more arrays to test, this will let you. It also de-dupes the individual arrays, so numbers within each are only counted once to prevent errors.
function findCommon() {
var obj = {};
var out = [];
var result = [];
// convert arguments to a proper array
var args = [].slice.call(arguments);
var len = args.length;
for (var i = 0, l = len; i < l; i++) {
// grab a de-duped array and and concatenate it
// http://stackoverflow.com/a/9229821/1377002
var unique = args[i].filter(function(item, pos) {
return args[i].indexOf(item) == pos;
});
result = result.concat(unique);
}
for (var i = 0, l = result.length; i < l; i++) {
var el = result[i];
// if the object key doesn't exist, create an array
// as the value; add the number to the array
if (!obj[el]) obj[el] = [];
obj[el].push(el);
}
for (var p in obj) {
// if the array length equals the original length of
// the number of arrays added to the function
// add it to the output array, as an integer
if (obj[p].length === len) out.push(+p);
}
return out;
}
findCommon(a, b, c, d); // [2]
In addition, this will find all multiple keys, so if you replace the 5 in d as 3, the result will be [2, 3].
DEMO which uses 4 arrays, multiple hits
DEMO which uses 5 arrays
Try this:
function findCommon()
{
var common=[];
for(i=0; i<a.length; i++)
{
if(b.indexOf(i) != -1 && c.indexOf(i) != -1 && d.indexOf(i) != -1)
{
common.push(i);
}
}
return common;
}
This will return array of common values between all four arrays. Here is the working fiddle.
Assuming you want something generic for X arrays and we are talking about integers this sounds to me like some bucket business.
var a = [11, 2, 3, 4],
b = [2, 6, 3, 5],
c = [4, 2, 20, 3],
d = [34, 2, 21, 5];
function findCommon()
{
var bucket = [];
var maxVal = 0;
var minVal = 0;
for(var i = 0; i < arguments.length; i++)
{
for(var j = 0 ; j < arguments[i].length ; j++)
{
var val = arguments[i][j];
bucket[val] = bucket[val] + 1 || 1;
if(val > maxVal)
{
maxVal = val;
}
else if(val < minVal)
{
minVal = val;
}
}
}
var retVal = 0;
var maxTimes = 0;
for(var i = minVal ; i <= maxVal ; i++)
{
var val = bucket[i];
if(val > maxTimes)
{
maxTimes = val;
retVal = i;
}
}
return retVal;
}
console.log(findCommon(a,b,c,d));
JSFIDDLE.
You cna use indexOf to resolve that:
array.indexOf(element) >=0 // it means that element is in array
or
array.indexOf(element) != -1
When you would be using jQuery, thre is a shorter version:
$.inArray(value, array)
More fancy way, would be to use filter (Filter):
function hasElement(element, index, array) {
return element.indexOf(i) >= 0;
}
filtered = [a,b,c,d].filter(hasElement);
filtered.length === 4
This Try,
will find the common number with number of times it repeated.
var a = [11, 2, 3, 4],
b = [2, 6, 3, 5],
c = [4, 2, 20, 3],
d = [34, 2, 21, 5],
result = [],
common = [];
var all = a.concat(b).concat(c).concat(d);
var commonNum=0;
var largestCounter=0
for(var i = 0; i< all.length-1; i++){
var counter=0;
if(a.indexOf(all[i])>-1) counter+=1;
if(b.indexOf(all[i])>-1) counter+=1;
if(c.indexOf(all[i])>-1) counter+=1;
if(d.indexOf(all[i])>-1) counter+=1;
if(counter>largestCounter)
{largestCounter = counter;
commonNum = all[i];
}
};
alert(commonNum+" with count " + largestCounter);

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