1

I have an array of objects(product list), and I am implementing the sorting logic to it. In order to make it a single source of truth, I made a id-product map, which looks something like this:

const prodsMap = {
  1 : {
    id : 1,
    name : 'abc',
    price : 4
  },
  2 : {
    id : 2,
    name : 'aac',
    price : 3
  }
}

Now in order to sort products I am doing this:

function sortString(data, propName) {
  return data.sort((obj1, obj2) => {
    const val1 = obj1[propName]
    const val2 = obj2[propName]

    if (val1 < val2) {
      return -1
    }

    if (val1 > val2) {
      return 1
    }

    return 0
  })
}

Calling the function like this:

const prods = sortString(Object.values(prodsMap), 'name')

Everything works fine here, the result of sorting will be an array of objects, in order to get the id's I am using map function.

Now the problem is that I've to iterate thrice(first to get object values, second to sort and third time to map id's), I was wondering if there is a better way to get only ID's when the array gets sorted.

8
  • and third time to map id's But the keys are already the ids..? (if they aren't, consider converting to an object structure so that they are) Commented Jun 25, 2018 at 6:58
  • @CertainPerformance sortString returns array of objects, so keys won't be there anymore. Commented Jun 25, 2018 at 6:59
  • btw, sort mutates the array. Commented Jun 25, 2018 at 6:59
  • @BharatSoni sortString returns the sorted Object.keys(prodsMap). But the keys are the IDs, not objects. You're not sorting an array of objects, you're sorting an array of keys. (you don't even have an array of objects anywhere here) Commented Jun 25, 2018 at 7:01
  • @NinaScholz yep. But Object.keys will always returns a new list and that list is passed to sorter. Commented Jun 25, 2018 at 7:02

1 Answer 1

3

You could order the keys of the handed over object, to get an array of id.

If you need the ìd property of the objects, you could map the values of the outer object with id property.

const prodsMap = {
  1 : {
    id : 1,
    name : 'abc',
    price : 4
  },
  2 : {
    id : 2,
    name : 'aac',
    price : 3
  }
}

function sortString(data, propName) {
  return Object.keys(data).sort((a, b) => {
    const val1 = data[a][propName];
    const val2 = data[b][propName];

    if (val1 < val2) {
      return -1;
    }

    if (val1 > val2) {
      return 1;
    }

    return 0;
  });
}

const prods = sortString(prodsMap, 'name');

console.log(prods);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.