Search code examples
javascriptreactjssortingreact-nativebubble-sort

How to merge 2 arrays based on a key name and sort based on the merged value?


assume I have two list

const listA = [{"apple":100}, {"banana": 50}, {"pearl": 10}, {"cherry": 5}, {"kiwi": 3}]
const listB = [{"peach": 30}, {"apple": 15}, {"kiwi": 10}, {"mango": 5}]

The question is how do I merge two list into one stack up the same item with number increment and sort by the qty? I mean the final result should be ->

const listMerged = [{"apple":115}, {"banana": 50} , {"peach": 30}, {"kiwi": 13}, {"pearl": 10}, {"cherry": 5}, {"mango": 5}]

I know it is gonna be something like :

sortListDesc(list) {

    return obj.sort(function (l1,l2) {
      return l2< l1 ? -1
           : l2 >l1 ? 1
           : 0
    })
  }

but do not know exactly how to stack up the number, than sort by qty number.


Solution

  • You can use reduce, and sort and Object.values like this:

    const listA = [{"apple":100}, {"banana": 50}, {"pearl": 10}, {"cherry": 5}, {"kiwi": 3}]
    , listB = [{"peach": 30}, {"apple": 15}, {"kiwi": 10}, {"mango": 5}]
    
    let merged = Object.values(listA.concat(listB).reduce((acc, a) => {
      const [k, v] = Object.entries(a)[0];
      (acc[k] = acc[k] || {[k]: 0})[k] += v;
      return acc;
    }, {}));
    
    merged.sort((a, b) => Object.values(b)[0] - Object.values(a)[0]);
    console.log(merged);

    Or,

    Using reduce, create an object with all the fruits as keys and individual sum as values. Then use Object.entries, sort and map like this:

    const listA = [{"apple":100}, {"banana": 50}, {"pearl": 10}, {"cherry": 5}, {"kiwi": 3}]
    , listB = [{"peach": 30}, {"apple": 15}, {"kiwi": 10}, {"mango": 5}]
    
    let merged2 = listA.concat(listB).reduce((acc, a) => {
      const [k, v] = Object.entries(a)[0];
      acc[k] = (acc[k] || 0) + v;
      return acc;
    }, {});
    
    const final = Object.entries(merged2)
      .sort(([, v1], [, v2]) => v2 - v1)
      .map(([k, v]) => ({[k]: v}))
    
    console.log(final);