Search code examples
javascriptarrayssortingdictionarysub-array

Sort array elements on JavaScript


I have an array, each subarray of which contains different positions in different order:

[
  ["apple(2)", "banana(5)"],
  ["peach(3)", "banana(1)"],
  ["apple(1)"]
]

I need to sort it on JavaScript (ES6) and i expect to get an array like this:

[
  ["apple(2)", "banana(5)", "peach(0)"],
  ["apple(0)", "banana(1)", "peach(3)"],
  ["apple(1)", "banana(0)", "peach(0)"]
]

Order of each subarray should be the same. If subarray don't have some position, i need to add it with 0 value. Can i using something like map() or sort() function or need to compare it manually?


Solution

  • Here is functional programming approach, using a Map and reduce:

    const data = [['apple(2)', 'banana(5)'],['peach(3)', 'banana(1)'],['apple(1)'],];
    
    // Create a Map with default values for each name, i.e. with "(0)":
    let names = new Map(data.flat().map(item => [item.replace(/\d+/, ""), item.replace(/\d+/, "0")]));
    let result = data.map(row =>
        [...row.reduce((map, item) => 
            map.set(item.replace(/\d+/, ""), item), // Overwrite default
            new Map(names) // Start with clone of original Map
        ).values()]
    );
    console.log(result);