Skip to content

Commit a68f47c

Browse files
authored
Add files via upload
0 parents  commit a68f47c

File tree

1 file changed

+80
-0
lines changed

1 file changed

+80
-0
lines changed

sortArrayOfObjects.js

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
const arrayOfObjects = [
2+
{
3+
firstName: 'victor',
4+
lastName: 'Ijoni',
5+
id: 1,
6+
sex: 'male',
7+
age: 28,
8+
cars: ['red', 'green', 'blue']
9+
},
10+
{
11+
firstName: 'Ruky',
12+
lastName: 'Choji',
13+
id: 11,
14+
sex: 'male',
15+
age: 14,
16+
cars: ['ford', 'green', 'blue']
17+
},
18+
{
19+
firstName: 'Caleb',
20+
lastName: 'Uzumaki',
21+
id: 09.5,
22+
sex: 'male',
23+
age: 14,
24+
cars: ['benz', 'green', 'blue']
25+
},
26+
{
27+
firstName: 'Itua',
28+
lastName: 'Minato',
29+
id: 5,
30+
sex: 'male',
31+
sex: 'male',
32+
age: 14,
33+
cars: ['camry', 'green', 'blue']
34+
},
35+
{
36+
firstName: 'shully',
37+
lastName: 'igbavwe',
38+
id: 3,
39+
sex: 'female',
40+
age: 16,
41+
nationality: 'Nigerian',
42+
cars: ['vox wagen', 'green', 'blue']
43+
},
44+
{
45+
firstName: 'esther',
46+
lastName: 'Hinata',
47+
id: 9.51,
48+
sex: 'female',
49+
age: 50,
50+
cars: ['tundra', 'green', 'blue']
51+
},
52+
{
53+
firstName: 'taiwo',
54+
lastName: 'Ajayi',
55+
id: 41,
56+
sex: 'male',
57+
age: 29,
58+
cars: ['mini bus', 'green', 'blue']
59+
}
60+
];
61+
62+
/**
63+
* Sorts an array of objects by a property present one level deep, in any object in the array. If successful, returns the sorted array of objects, else the original array is returned.
64+
* @param {Array<Object>} arrayOfObjects
65+
* @param {String} property
66+
* @returns {Array<Object>} sortedArrayOfObjects
67+
*/
68+
const sortArrayOfObjects = (arrayOfObjects, property) => {
69+
if (!arrayOfObjects) return arrayOfObjects;
70+
if (!Array.isArray(arrayOfObjects)) return arrayOfObjects;
71+
if (arrayOfObjects.length <= 1) return arrayOfObjects;
72+
let isInt = false;
73+
return arrayOfObjects.map((el, index) => {
74+
isInt = !isNaN(el?.[property]);
75+
return !isInt ?
76+
`${el?.[property]?.[0]?.toUpperCase()?.concat(el?.[property]?.slice(1))}^-.-^${index}` :
77+
`${el?.[property]}^-.-^${index}`;
78+
})?.sort(isInt ? (a, b) => Number(a?.split('^-.-^')?.[0]) - Number(b?.split('^-.-^')?.[0]) : undefined)?.map(el => arrayOfObjects[el?.split('^-.-^')?.[1]]);
79+
};
80+
console.log(sortArrayOfObjects(arrayOfObjects, 'cars'));

0 commit comments

Comments
 (0)