I'm trying to reverse the contents of an array. My approach works well when the contents of the said array are of same type. but once they're of different types it just doesn't work.
Constraint is that i can't use the .reverse()
method and if possible, without creating a new array.
The answer in this question is close to what i want but i don't understand it.
Here is my code...
reverse.js
#!/usr/bin/node
exports.rev = function (list) {
for (let i = 0, j = (list.length - 1); i <= (list.length / 2); i , j--) {
[list[i], list[j]] = [list[j], list[i]];
}
return (list);
};
main.js
#!/usr/bin/node
const rev = require('./reverse').rev;
console.log(rev([1, 2, 3, 4, 5]));
console.log(rev(["School", 89, { id: 12 }, "String"]));
Expected:
[5, 4, 3, 2, 1]
["String", { id: 12 }, 89, "School"]
What I got:
[5, 4, 3, 2, 1]
["String", 89, { id: 12 }, "School"]
CodePudding user response:
I've found out that your code almost works. You just need to modify the condition a bit to
i < (list.length / 2) //not `<=`
function rev(list) {
for (let i = 0, j = (list.length - 1); i < (list.length / 2); i , j--) {
[list[i], list[j]] = [list[j], list[i]];
}
return (list);
};
console.log(rev([1, 2, 3, 4, 5]));
console.log(rev(["School", 89, { id: 12 }, "String"]));
CodePudding user response:
let array = [1, 2, 3, 4, 5]
let reverse = [];
for (var i = array.length - 1; i >= 0; i--){
reverse.push(array[i]);
}
CodePudding user response:
You can try with a for
loop like this:
let arr = ["School", 89, { id: 12 }, "String"];
let newArr = [];
for (let i = arr.length - 1; i >= 0; i--) {
newArr.push(arr[i])
}
console.log(newArr);
Expected output: ["String", [object Object] { id: 12 }, 89, "School"]
CodePudding user response:
You can user a recursion to reverse
You can use Spread operator(...
) along with distructure assignment for that.
function rev(arr) {
const [first, ...rest] = arr
return arr.length > 1 ? [...rev(rest), first] : arr
}
console.log(rev([1, 2, 3, 4, 5]));
console.log(rev(["School", 89, { id: 12 }, "String"]));
const [first, ...rest] = arr
is a shortcut for:
const first = arr[0]
const rest = arr.slice(1)
However, ...rev(rest)
will spread items of returned array and spread them. So, [...rev(rest), first]
will keep the output of rev first and then push first
at the end of array.
If you are comfortable with mutation of original array, try this
function rev(arr) {
return arr.length > 1 ? [arr.pop(), ...rev(arr)] : arr
}
console.log(rev([1, 2, 3, 4, 5]));
console.log(rev(["School", 89, { id: 12 }, "String"]));
CodePudding user response:
Already good answers (and examples of arrays) here
My try with native methods:
const rev = (arr) => {
len = arr.length;
for (i = 1; i<= len; i ) arr.splice(len-i,0,arr.shift());
}
const array = ["School", 89, { id: 12 }, "String"];
console.log("original",array);
rev(array);
console.log("reversed",array);