dimanche 19 juillet 2020

JavaScript - Improvement of the dynamic array of object. Maintenance of repetitions

I have this script:

console.log(solution([2, 1, 3, 5, 3, 2]))

function solution(inputArray) {
  let arrMap = []
  
  for (let i = 0; i < inputArray.length; i++) {   
    var e = arrMap.find(s => s.element == inputArray[i])

    if (e) {
      e.repeated = true;
      e.firstPosition = e.position
      e.lastPosition = i
      e.quantity++
      delete e['position'];
    
    } else {
      arrMap.push({
        repeated: false,
        element: inputArray[i],
        position: i,
        quantity: 1
      })
    }
  }  
  
 return arrMap    
}

The script returns a dynamically constructed object:

[
  {
    repeated: true,
    element: 2,
    quantity: 2,
    firstPosition: 0,
    lastPosition: 5
  },
  { repeated: false, element: 1, position: 1, quantity: 1 },
  {
    repeated: true,
    element: 3,
    quantity: 2,
    firstPosition: 2,
    lastPosition: 4
  },
  { repeated: false, element: 5, position: 3, quantity: 1 }
]

I would like to keep only a couple of elements that repeat themselves. In case we have that entry:

/*           pairs:    V     V     V  V        */   
 console.log(solution([2, 1, 3, 5, 3, 2, 2]))
/*                                       ^
                                         | DO NOT INCLUDE THIS ITEM IN THE 
                                         | OUTPUT ARRAY! ITEM LEFT!
/*

I would like to NOT include this last item, in this case 2. Because in that case we will have one left out of the pair. I just want to accept only a couple of elements at most.

In this another example below I would also like to NOT include this pair more than allowed. I must remember that I will only accept one pair of each. How do I do?

/*            pairs:  V     V     V  V            */
console.log(solution([2, 1, 3, 5, 3, 2, 2, 2]))
/*                                      ^  ^
                                        |  |

                                      DO NOT INCLUDE THESE 2 ITEMS IN THE 
                                      OUTPUT ARRAY! PAIR LEFT!
                                      --------------------------------- 
                                      I Already have a pair 
                                      with this item!
*/

Aucun commentaire:

Enregistrer un commentaire