1
votes

I have a large Object containing addresses and numbers.

{
  '0x2bac18ad331A3137AbEC3a029dBb3A6cC25835ea': 1,
  '0x22Bf3f4EA7862739024C122aDDd2FB2981c076a7': 3,
  '0x9E6E8b584F26503C84661674dCD7821099c8a51d': 1,
  '0x37D74ca0F842817C6FC4Ea267cF2d49DEa0C06a8': 1,
  '0xDf92913902087aD0Bfac39659B60CebE1100595a': 1
// ...
}

and I try to swap key/values and store all addresses with the same number value in an Array, thinking of something like this:

var newObj = {
 "1": [addr1, addr2, addr3],
 "2": [addr1, addr2, addr3],
 "3": [addr1, addr2, addr3]
//...
}

I found a way to swap like this:

function swaptoArray(json){
    var ret = {};
    for(var key in json){
    ret[json[key]] = key;
    }
    return ret;
  }

but I am having trouble making the value-part an Array containing many addresses. I tried this, but don't understand the wrong result. Any hints?

function swaptoArray(json){
    var ret = {};
    var newArray = [];

    for(var key in json){

      ret[json[key]] = newArray.push(key);

    }
    return ret;
  }

Result:

{ '1': 5, '3': 2 }
2
newArray.push(key) returns the new length of the arrayBravo

2 Answers

0
votes

You need an array as result for every value as key for the result.

function group(object) {
    const result = {};
    for (const key in object) (result[data[key]] ??= []).push(key);
    return result;
}

const data = {
  '0x2bac18ad331A3137AbEC3a029dBb3A6cC25835ea': 1,
  '0x22Bf3f4EA7862739024C122aDDd2FB2981c076a7': 3,
  '0x9E6E8b584F26503C84661674dCD7821099c8a51d': 1,
  '0x37D74ca0F842817C6FC4Ea267cF2d49DEa0C06a8': 1,
  '0xDf92913902087aD0Bfac39659B60CebE1100595a': 1
}

console.log(group(data));
0
votes

Here's a solution using Object.entries:

const obj = {
  '0x2bac18ad331A3137AbEC3a029dBb3A6cC25835ea': 1,
  '0x22Bf3f4EA7862739024C122aDDd2FB2981c076a7': 3,
  '0x9E6E8b584F26503C84661674dCD7821099c8a51d': 1,
  '0x37D74ca0F842817C6FC4Ea267cF2d49DEa0C06a8': 1,
  '0xDf92913902087aD0Bfac39659B60CebE1100595a': 1
}

const objArr = Object.entries(obj)

function getArray(key) {
  let ret = []
  objArr.forEach(item => {
    if(item[1] === key) ret.push(item[0])
  })  
  return ret
}

function swaptoArray(json) {
  let ret = {}
  for (let key in json) {
    const newKey = json[key]
    ret[newKey] = getArray(newKey)
  }
  return ret
}

console.log(swaptoArray(obj))