0
\$\begingroup\$

I've written some code that is yielding the desired results but it seems verbose. The code gets the distinct objects from an array of objects when looking at only a subset of the keys. Is there a more concise way to write the code to get the same output?

const source = [
    {"id":"1","department":"grocery","storeLocation":"downtown","shelf":"21","slot":"A12","item":"celery"},
    {"id":"2","department":"hardware","storeLocation":"mall","shelf":"57","slot":"452","item":"flashlights"},
    {"id":"3","department":"grocery","storeLocation":"downtown","shelf":"21","slot":"B17","item":"cabbage"},
    {"id":"4","department":"grocery","storeLocation":"downtown","shelf":"21","slot":"D28","item":"lettuce"},
    {"id":"5","department":"hardware","storeLocation":"mall","shelf":"57","slot":"493","item":"duct tape"}
];

const distinctCombinations = {};
source.forEach(o => {
    distinctCombinations[o.storeLocation] = { storeLocation: o.storeLocation, department: o.department, shelf: o.shelf }
});

const result = Object.values(distinctCombinations);

console.log(result);

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

Here is what I came up with:

const source = [
    {"id":"1","department":"grocery","storeLocation":"downtown","shelf":"21","slot":"A12","item":"celery"},
    {"id":"2","department":"hardware","storeLocation":"mall","shelf":"57","slot":"452","item":"flashlights"},
    {"id":"3","department":"grocery","storeLocation":"downtown","shelf":"21","slot":"B17","item":"cabbage"},
    {"id":"4","department":"grocery","storeLocation":"downtown","shelf":"21","slot":"D28","item":"lettuce"},
    {"id":"5","department":"hardware","storeLocation":"mall","shelf":"57","slot":"493","item":"duct tape"}
];

const distinctCombinations = [...new Set(source.map(o => JSON.stringify(o, ['storeLocation', 'department', 'shelf'])))].map(o => JSON.parse(o));

console.log(distinctCombinations);

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.