0

I have a JS object that looks like this:

{
'abc': {'time': 1, 'data': 100},
'wad': {'time': 3, 'data': 200},
'gfd': {'time': 2, 'data': 700},
'qwe': {'time': 4, 'data': 344},
}

how can I easily remove the "oldest" X (2 in this case) entries (time 1 & 2) and get the following object:

{
'wad': {'time': 3, 'data': 200},
'qwe': {'time': 4, 'data': 344},
}
isherwood
  • 58,414
  • 16
  • 114
  • 157
user6097845
  • 1,257
  • 1
  • 15
  • 33
  • Did you try the most obvious approach: object.entries, then sort, then remove the first/last (depending on your sort order) 2 entries, then object.fromEntries? – Wyck Aug 10 '21 at 18:13
  • 1
    You're asking how to [sort](https://stackoverflow.com/questions/1069666/sorting-object-property-by-values) and how to [slice](https://stackoverflow.com/questions/28807751/is-it-possible-to-slice-an-object). Both have been covered well. – isherwood Aug 10 '21 at 18:19

2 Answers2

1

Sort by time, slice off the first N elements:

const result = Object.fromEntries(Object.entries({
'abc': {'time': 1, 'data': 100},
'wad': {'time': 3, 'data': 200},
'gfd': {'time': 2, 'data': 700},
'qwe': {'time': 4, 'data': 344},
}).sort((a, b) => a[1].time - b[1].time).slice(2))

console.log(result);
dave
  • 62,300
  • 5
  • 72
  • 93
1

You can use a method to make your solution dynamic:

Method 1 is:

const removeOldItems = (obj, numbItems) => {
   const keys = Object.keys(obj);
   if(numbItems > keys.length) return; // you can handle this error here
   const updatedKeys = keys.sort((a, b)=>obj[a].time - obj[b].time).slice(numbItems);
   const newObj = {};
   updatedKeys.forEach(k => Object.assign(newObj, {[k]:obj[k]}));
   return newObj;
}

Or method 2 as derived from @dave's answer - if you prefer shortened form:

const removeOldItems = (obj, numbItems) => {
    const keys = Object.keys(obj);
    if(numbItems > keys.length) return; // handle this error here if needed
    return Object.fromEntries(Object.entries(obj).sort((a, b) => a[1].time - b[1].time).slice(numbItems))
  }

Then just call it with any number of old items you want to get rid of:

const obj = {
'abc': {'time': 1, 'data': 100},
'wad': {'time': 3, 'data': 200},
'gfd': {'time': 2, 'data': 700},
'qwe': {'time': 4, 'data': 344},
}
// Using object copies
console.log(removeOldItems({...obj}, 1)) //remove 1 old item
console.log(removeOldItems({...obj}, 2)) //remove 2 old item
console.log(removeOldItems({...obj}, 3)) //remove 3 old item
briancollins081
  • 845
  • 9
  • 19