0

I have the following array:

const result = [
  [{value: 123, parentID: 1}, {value: 'string123', parentID: 2}],
  [{value: 54764, parentID: 1}, {value: 'string321', parentID: 2}],
  [{value: 321, parentID: 1}, {value: 'string565632', parentID: 2}],
]

and I need to sort this, multidimensional array based on the value, but which object to select is based on parentID.

What I have tried so far:

const parentID = 1;
const sortedResult = result.filter((row) => {
  const selectedColumn = row.find((column) => column.parentID === parentID));
  return _.orderBy(selectedColumn, ['value'], ['asc']);
});

but this isn't working, any ideas what could?

Desired output would be:

[
  [{value: 123, parentID: 1}, {value: 'string123', parentID: 2}],
  [{value: 321, parentID: 1}, {value: 'string565632', parentID: 2}],
  [{value: 54764, parentID: 1}, {value: 'string321', parentID: 2}],
]
1
  • @CBroe so all of the objects have a value property and a parentID property. In order to choose by which object to sort, you would use parentID. Commented May 18, 2020 at 11:49

1 Answer 1

1

To sort an array, you should use Array.prototype.sort.

Make a helper function that, given an array item (which, here, is itself an array), finds the object with the parentID, and extracts its value. In the .sort callback, call that helper function on both items being compared, and return the difference:

const parentID = 1;
const getValue = arr => arr.find(item => item.parentID === parentID).value;
const result = [
  [{value: 123, parentID: 1}, {value: 'string123', parentID: 2}],
  [{value: 54764, parentID: 1}, {value: 'string321', parentID: 2}],
  [{value: 321, parentID: 1}, {value: 'string565632', parentID: 2}],
];
result.sort((a, b) => getValue(a) - getValue(b));
console.log(result);

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.