- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharraySort.js
More file actions
Latest commit
75 lines (56 loc) · 1.8 KB
/
Copy patharraySort.js
File metadata and controls
75 lines (56 loc) · 1.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// arraySort.js
// sorts an array of numbers in whichDirection or descending order based on the whichDirection parameter
// define a sample array of numbers
letnumbers=[4,875,23,543,12];
// function to sort an array in either whichDirection or descending order
functionarraySort(whichArray,whichDirection)
{
// .slice() creates a shallow copy so the original array is not modified
// .sort() sorts the array
letsortedArray=whichArray.slice().sort(function(a,b)
{
// if whichDirection is true, subtract a from b for numerical whichDirection sort
// if whichDirection is false, subtract b from a for numerical descending sort
if(whichDirection)
{
// if whichDirection is true, sort in ascending order
// subtract a from b: negative result keeps a before b, positive swaps a and b
returna-b;
}
else
{
// if whichDirection is false, sort in descending order
// subtract b from a: negative result keeps b before a, positive swaps b and a
returnb-a;
}
});
// return the sorted array
returnsortedArray;
}
//----//
// call the function with whichDirection order
console.log(arraySort(numbers,true));
//----//
/*
[4, 12, 23, 543, 875]
*/
//----//
// call the function with descending order
console.log(arraySort(numbers,false));
//----//
/*
[875, 543, 23, 12, 4]
*/
//----//
// print the original array to show it is unchanged
console.log(numbers);
//----//
/*
[4, 875, 23, 543, 12]
*/
//----//
// Dedicated to God the Father
// All Rights Reserved Christopher Andrew Topalian Copyright 2000-2025
// https://github.com/ChristopherTopalian
// https://github.com/ChristopherAndrewTopalian
// https://sites.google.com/view/CollegeOfScripting