skip to Main Content

I have a question

I have an array group like this :

myArray = { tab1 : [], tab2 : [], tab3 : [], tab4 : [] }

I want to always keep my first tab (tab1) and to keep an additionnal tab using an index (which value is between 2 and 4)

For example : if my index value is 2, I want to keep the tab2 and obtain this :

myArray = { tab1 : [], tab2 : [] }

Thanks

2

Answers


  1. You can use Array.prototype.reduce to do something like this

    Object.entries(myArray).reduce((acc, [key, value], index) => {
      // Check if it is the first element or the one to keep
      if (!index || index === indexToKeep) {
        acc[key] = value;
      }
      return acc;
    }, {});
    

    Here Object.entries(myArray) will transform your object into an 2d array of key / value

    [
      ['tab1', [/* Value of myArray.tab1 */]], 
      ['tab2', [/* Value of myArray.tab2 */]], 
      // etc...
    ]
    
    Login or Signup to reply.
  2.     let myArray = { tab1: [], tab2: [], tab3: [], tab4: [] };
        const index = 2; // it could be 3 or 4 ....
        
        // Remove additional tabs based on the index value
        for (let key in myArray) {
          if (key !== 'tab1' && key !== `tab${index}`) {
            delete myArray[key];
          }
        }
        
        console.log(myArray);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search