Search code examples
javascriptarraysobjectdynamic

Dynamic Javascipt array manipulation


let say I have example input data,

data = [
  { name : 'Alice', age : 21},
  { name : 'Henry', age : 20 },
  { name : 'Max', age : 20 },
  { name : 'Jane', age : 21}
]

and I somehow want to merge them and turn this data into following form,

result = [
  { age : 20, name : ['Henry', 'Max'] },
  { age : 21, name : ['Alice', 'Jane'] } 
]

I do not want to solve this with specific name of key or value. I want to handle dynamically. Thank you!


Solution

  • Here is a quick example that shows the type of iteration/mapping/manipulation you can use to turn arbitrary data sets into a grouping as you propose:

    https://jsfiddle.net/6b2rp4n7/

    const data = [
      { name : 'Alice', age : 21},
      { name : 'Henry', age : 20 },
      { name : 'Max', age : 20 },
      { name : 'Jane', age : 21}
    ];
    
    const mapping = new Map();
    
    for (var i = 0; i < data.length; i++) {
        const element = data[i];
      for (const prop in element) {
        const key = prop + "" + element[prop];
        if (mapping.get(key) != null && mapping.get(key).val === element[prop]) {
            const matches = mapping.get(key);
          matches.list.push(element);
        } else {
            const matches = {val: element[prop], key: prop, list: [element]};
          mapping.set(key, matches);
        }
      }
    }
    
    let result = [];
    mapping.forEach((val, key) => {
        if (val.list.length > 1) {
        let res = { matches: val.list };
        res[val.key] = val.val;
        result.push(res);
      }
    });
    
    console.log(result);
    

    Output:

    0:
    age: 21
    matches: Array(2)
    0: {name: "Alice", age: 21}
    1: {name: "Jane", age: 21}
    1:
    age: 20
    matches: Array(2)
    0: {name: "Henry", age: 20}
    1: {name: "Max", age: 20}
    

    I decided to exclude all groupings of a single element, though those could be valid as well. I also left the value manipulation to you - there should be enough to go on here to build up the data structure you desire. It is difficult to help much more beyond this without additional context on what you are trying to achieve and why. Good luck!