Group array multiple item in another array

azdaj zdnakjdnaz :

This is my Array:

    myArray = [
        {group: "one", version: 1.1, old: 0.1},
        {group: "two", version: 2.1, old: 1.1},
        {group: "one", version: 1.2, old: 0.2},
        {group: "one", version: 1.3, old: 0.3}
    ]

I want to convert into this (need to retrieve only the bigger and smaller version) :

myArray = [
 {group: "one", recentVersion: 1.3, oldVersion:0.1 }
 {group: "two", recentVersion: 2.1, oldVersion:1.1}
 ]

What I'm trying:

const groups = {};
    for (let i = 0; i < myArray.length; i++) {
        const groupName = diffList[i].group;
        if (!groups[groupName]) {
            groups[groupName] = [];
        }
        groups[groupName].push(diffList[i].version);
    }
    const myArray = [];
    for (const groupName in groups) {
        myArray.push({ group: groupName, recentVersion: groups[groupName});
    }
    console.log(myArray);

Actual result :

myArray = [
 {group: "one", recentVersion: [1.1,1.2,1.3]}
 {group: "two", recentVersion: [2.2]}
 ]

I don't know how to retrieve the bigger and smaller version and how push oldVersion...

vishnu sandhireddy :

You could set the old and recent version every time by comparing in the first for loop

let diffList = [
  { group: "one", version: 1.1, old: 0.1 },
  { group: "two", version: 2.1, old: 1.1 },
  { group: "one", version: 1.2, old: 0.2 },
  { group: "one", version: 1.3, old: 0.3 }
];
const groups = {};
for (let i = 0; i < diffList.length; i++) {
  const groupName = diffList[i].group;
  if (!groups[groupName]) {
    groups[groupName] = {
      recentVersion: diffList[i].version,
      oldVersion: diffList[i].old
    };
  }
  if (groups[groupName].recentVersion < diffList[i].version) {
    groups[groupName].recentVersion = diffList[i].version;
  }
  if (groups[groupName].oldVersion > diffList[i].old) {
    groups[groupName].oldVersion = diffList[i].version;
  }
}
let myArray = [];
for (const groupName in groups) {
  myArray.push({
    group: groupName,
    recentVersion: groups[groupName].recentVersion,
    oldVersion: groups[groupName].oldVersion
  });
}
console.log(myArray);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=29726&siteId=1