skip to Main Content

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


  1. 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.

    export const sliceData = (dataToSlice: []) =>
    {
    
      if(dataToSlice.length>=2 && dataToSlice.length<=10){
         return dataToSlice; // return schedule unchanged
      }
      
      // Otherwise return last 10 element of schedule
      return dataToSlice.slice(-10);
    }
    

    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:

    export const sliceData = (dataToSlice: Schedule[], fromLastElement: number) =>
    {
    
      if(dataToSlice.length>=2 && dataToSlice.length<=10){
         return schedule; // return schedule unchanged
      }
      
      // Otherwise return last 10 element of schedule
      return dataToSlice.slice(-fromLastElement);
    }
    
    Login or Signup to reply.
  2. I guess the issue is you are pushing a single object into the result and waiting for whole myArr to be returned. Also you are checking the result.length instead of the myArr 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.

    export const slicedData = (myArr:any[]) =>
    {
      if(myArr.length>=2 && myArr.length<=10){
         return myArr;
      }
    
      return result.slice(-15);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search