Skip to content

Javascript logic to sort object based on contains logic

I have an object as shown below: {abc: value1, ab: value2, ade: value3, cde: value4, fgi: value5}

I want to write a function sortByinput(input) that takes input as an argument and sort the given dictionary in such a way that the keys that include input should be sorted at top in alphabetical order and the keys then the rest of all below it. So for example:

sortByInput("a") for the object {abc: value1, ab: value2, ade: value3, cde: value4, fgi: value5} should return: {ab: value2, abc: value1, ade: value3, cde: value4, fgi: value5}

and sortByInput("c") for the object

{abc: value1, ab: value2, ade: value3, cde: value4, fgi: value5}

should return:

{cde: value4, ab: value2, abc: value1, ade: value3, fgi: value5}

Answer

Using Object.keys, you can get all keys in the input object and sort that keys using Array.prototype.sort.

And based on the sorted keys, you can get the new sorted object by assigning the sorted key value to the new object inside Array.prototype.map.

function sortByInput(input, startKey) {
  const sortedKeys = Object.keys(input).sort((a, b) => {
    const aCheck = a.startsWith(startKey); // Check if a starts with the startKey
    const bCheck = b.startsWith(startKey); // Check if b starts with the startKey
    
    if (aCheck && !bCheck) { // If a starts with startKey but not b
      return -1; // Keep the position
    }
    if (!aCheck && bCheck) { // If b starts with startKey but not b
      return 1; // Exchange the position
    }
    
    return a > b;
  });
  
  const output = {};
  sortedKeys.map((key) => output[key] = input[key]);
  return output;
}

const input = {
  abc: 'value1',
  ab: 'value2',
  ade: 'value3',
  cde: 'value4',
  fgi: 'value5'
};

console.log(sortByInput(input, 'a'));
console.log(sortByInput(input, 'c'));