skip to Main Content
var listx = [
    
    {
    name: 'user:20',
    id: '1720620993953-0'
  },
  {
    name: 'user:30',
    id: '1720621228109-0'
  },
   {
    name: 'user:30',
    id: '1720572420832-0'
  },
  
  {
    name: 'user:30',
    id: '1720572410558-0'
  },
  
]

I’m trying to get the max id for each name, and the name can repeat like shown below.

So for the example, it would be a Map:

'user:20': '1720620993953-0'
'user:30': '1720621228109-0'

I tried searching everything, but didn’t get a response.

3

Answers


  1. You can iterate through each item in the list. Then for each item, check if the id is greater than the already existing value and "save" it if it is.

    var listx = [
      {
        name: "user:20",
        id: "1720620993953-0",
      },
      {
        name: "user:30",
        id: "1720621228109-0",
      },
      {
        name: "user:30",
        id: "1720572420832-0",
      },
      {
        name: "user:30",
        id: "1720572410558-0",
      },
      {
        name: "user:30",
        id: "1720621228109-0",
      },
      {
        name: "user:30",
        id: "2000572420832-0",
      },
      {
        name: "user:20",
        id: "1720620993953-1",
      },
      {
        name: "user:20",
        id: "1000620993953-0",
      },
      {
        name: "user:30",
        id: "1720572410558-0",
      },
    ];
    
    var answers = {};
    listx.forEach((val) => {
      if (answers[val.name] == null) answers[val.name] = val.id;
      else if (val.id.localeCompare(answers[val.name]) == 1)
        answers[val.name] = val.id;
    });
    
    console.log(answers);
    Login or Signup to reply.
  2. You can simply iterate over the objects and aggregate these data in a new object, conditionally setting the id value:

    const listx = [{name: 'user:20',id: '1720620993953-0'}, {name: 'user:30',id: '1720621228109-0'}, {name: 'user:30', id: '1720572420832-0'}, {name: 'user:30',id: '1720572410558-0'}];
    const grouped = {};
    for (const {name, id} of listx) {
        if (!(id < grouped[name])) grouped[name] = id;
    }
    console.log(grouped);
    Login or Signup to reply.
  3. Use Array.prototype.reduce() to run through the list and build the desired result:

    const list = [
      {
        name: 'user:20',
        id: '1720620993953-0'
      },
      {
        name: 'user:30',
        id: '1720621228109-0'
      },
      {
        name: 'user:30',
        id: '1720572420832-0'
      },
      {
        name: 'user:30',
        id: '1720572410558-0'
      }, 
    ];
    
    
    const max = list.reduce(
      (acc, curr) => {
        const id = acc[curr.name];
        if (id !== undefined) {
          acc[curr.name] = curr.id < id ? id : curr.id;
        } else {
          acc[curr.name] = curr.id;
        }
    
        return acc;
      },
      new Map()
    );
    
    
    console.log(max);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search