Skip to content

Commit 0101745

Browse files
committed
reverse array without sort
1 parent f4ffeb8 commit 0101745

File tree

2 files changed

+56
-0
lines changed

2 files changed

+56
-0
lines changed
+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
# 0010 reverseArrayWithoutSort ( L-B )
2+
3+
## Problem
4+
5+
Implement a JavaScript function that takes an array of numbers and returns a new array with the numbers in reverse order.
6+
7+
## Test Cases
8+
9+
- console.log(reverseArray([1, 2, 3, 4, 5])); // [5, 4, 3, 2, 1]
10+
- console.log(reverseArray([9, 9, 2, 3, 4])); // [4, 3, 2, 9, 9]
11+
12+
## Solution
13+
14+
```javascript
15+
function reverseArray(arr) {
16+
const result = [];
17+
for (let i = arr.length - 1; i >= 0; i--) {
18+
result.push(arr[i]);
19+
}
20+
return result;
21+
}
22+
```
23+
24+
## How it works
25+
26+
- We create a function called reverseArray that takes an array as a parameter.
27+
- We create a result array.
28+
- We loop through the array backwards.
29+
- We push the current element to the result array.
30+
- We return the result array.
31+
32+
## References
33+
34+
- [freecodecamp](https://www.freecodecamp.org/news/how-to-reverse-an-array-in-javascript-in-3-different-ways-75e4763c68cb/)
35+
- [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse)
36+
37+
## Problem Added By
38+
39+
- [GitHub](https://www.github.com/devvsakib)
40+
- [LinkedIn](https://www.linkedin.com/in/devvsakib)
41+
- [Twitter](https://twitter.com/devvsakib)
42+
43+
## Contributing
44+
45+
Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.
46+
47+
Please make sure to update tests as appropriate.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
function reverseArray(arr){
2+
var newArr = [];
3+
for(var i = arr.length-1; i >= 0; i--){
4+
newArr.push(arr[i]);
5+
}
6+
return newArr;
7+
}
8+
const arr = [1,2,3,4,5,6,7,8,9,10];
9+
console.log(reverseArray(arr))

0 commit comments

Comments
 (0)