Home > Back-end >  Removing elements from an array of objects with the same properties and comparing different properti
Removing elements from an array of objects with the same properties and comparing different properti

Time:06-17

I have a Javascript project in which I am eliminating the same objects that the array contains.

This is my project:

let dataObj = [
  {
    "test1": "model",
    "test2": "dataFile",
    "test3": "2022-06-15"
  },
  {
    "test1": "model",
    "test2": "dataFile",
    "test3": "2022-06-10"
  },
  {
    "test1": "data",
    "test2": "mode",
    "test3": "2022-06-08"
  }
]
    
let result = Object.values(dataObj.reduce((acc,cur)=>Object.assign(acc,{[cur.test1]:cur}),{}))
    
console.log(result)

My problem:

  1. Now I can only filter by one key ('test1'), I need to know how to filter by several keys
  2. The first two objects are the same, how can I get the object where the value of the 'test3' property is greater?

CodePudding user response:

Unless I'm misunderstanding, this should work.

const result = dataObj.reduce((mostRecentObject, currentObject) => {
  const mostRecentObjectTime = Date(mostRecentObject['test3'].getTime()
  const currentObjectTime = Date(currentObject['test3'].getTime()

  const currentObjectIsMoreRecent = currentObjectTime > mostRecentObjectTime

  return currenctObjectIsMoreRecent ? currentObject : mostRecentObject
}, dataObj[0])

This should return the object within the dataObj array where the value of test3 is the most recent.

CodePudding user response:

You could iterate the array directly without getting values from the object, which ist an additional superfluous step.

For using more than one key, take an array of keys and build a combined hash value and get the values later. If you have different values in other properties, you could get either the first

r[key] ??= o;

or last

r[key] = o;

item, depending of the used algorithm.

For taking only an object with recent date, take a check before the assigning.

if (!r[key] || r[key].test3 < o.test3) r[key] = o;

const
    data = [
        { test1: "model", test2: "dataFile", test3: "2022-06-15" },
        { test1: "model", test2: "dataFile", test3: "2022-06-10" },
        { test1: "data", test2: "mode", test3: "2022-06-08" },
        { test1: "data", test2: "raw", test3: "2022-01-01" }
    ],
    keys = ['test1', 'test2'],
    result = Object.values(data.reduce((r, o) => {
        const key = keys.map(k => o[k]).join('|');
        if (!r[key] || r[key].test3 < o.test3) r[key] = o;
        return r;
    }, {}));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

  • Related