I have the array and need to divide 3 student per 3 array. Need to get the following results per cases:
-
sortStudentsByGroups(students)
=>[ [ 'Andrew', 'Ann', 'Bernard' ], [ 'Cris', 'Josh', 'Mark' ], [ 'Peter', 'Sam', 'Sandra' ], 'Rest students: Takesi']
-
if to delete one student from the list, will get:
[ [ 'Andrew', 'Ann', 'Bernard' ], [ 'Cris', 'Josh', 'Mark' ], [ 'Peter', 'Sam', 'Sandra' ], 'Rest students: -' ]
My CODE:
const students = [
"Peter",
"Andrew",
"Ann",
"Mark",
"Josh",
"Sandra",
"Cris",
"Bernard",
"Takesi",
"Sandra",
];
function sortStudentsByGroups(arr) {
arr.sort();
const arrNew = [];
const arr_size = 3;
for (let i = 0; i < arr.length; i += arr_size) {
let y = arr.slice(i, i + arr_size);
arrNew.push(y);
if (y.length < 3) {
let u = y.join(", ");
arrNew.push(`Rest students: ${u}`);
}
}
console.log(arrNew);
}
sortStudentsByGroups(students);
For 1 option I have correct result:
[
[ 'Andrew', 'Ann', 'Bernard' ],
[ 'Cris', 'Josh', 'Mark' ],
[ 'Peter', 'Sandra', 'Sandra' ],
[ 'Takesi' ],
'Rest students: Takesi'
]
And don’t know how to get result for 2-nd option, exactly add to arr ‘Rest students: -‘
[
[ 'Andrew', 'Ann', 'Bernard' ],
[ 'Cris', 'Josh', 'Mark' ],
[ 'Peter', 'Sam', 'Sandra' ],
'Rest students: -'
]
I tried to push in array and as the result iterating every time
4
Answers
One possibility would be to distribute normally, then pick the last element and check its size:
you can do your function like that:
You have handled the case, when you have "y" value <3 i.e, if y is 3, then you have appended right? so if the no. of people are multiple of 3 only, your 2nd test case fails.
so, you can add else condition here,
Move your rest students logic outside the loop and use
to get the remaining students and join them with
,
.If the string is empty that means no students left, so add
|| '-'
to display the dash.Btw you mutate the original array with
sort()
. If that’s not desired, just copy the array:arr = arr.slice().sort()
.