I have an array:
myArr= [
{"name":"John", "schedule": [{"course":"ESL", "hours": 25},{"course": "Math", "hours": 50},{"course": "History", "hours": 75}]},
{"name":"Julia", "schedule": [{"course":"English", "hours": 20},{"course": "Geography", "hours": 35},{"course": "Math", "hours": 55}]},
{"name":"Adam", "schedule": [{"course":"Physics", "hours": 15},{"course": "Math", "hours": 50},{"course": "Chemistry", "hours": 60}]}
];
if the length of myArr is more than 2 or less than 10, need return myArr unchanged, but if it more than 10 then need to return last 15 objects of array.
I wrote function, but array returns empty.
export const slicedData = (schedule:Schedule[], name:string) =>
{
const result:Schedule[] = [];
result.push({name, schedule});
if(result.length>=2 && result.length<=10){
return result;
}
return result.slice(-9);
}
please advise what i am missing?
2
Answers
As @jsejcksn wrote in comment, you should use AND (&&) operator instead of OR (||). This guarantee that the value is between 2 and 10.
Again, as @Martijn noticed, you are creating an array with just one value. If you already have
myArr
you should pass it to function and use it.If you don’t have the array, is a good idea to create a function that first create your desired array and the call
sliceData
.A little improvement could be to pass the number of last elements to return:
I guess the issue is you are pushing a single object into the
result
and waiting for wholemyArr
to be returned. Also you are checking theresult.length
instead of themyArr
length when comes to pushing. And if you want to have the last 15 objects of array you need to use-15
instead of-9
. With these changes code should be like below.