For each object, construct a Map
whose keys are fruit strings and values are the associated original number in the c
array. Sort the c
array, then sort the b
array based on the difference between the items in the map:
const arr = [
{a: 1, b: ['apple', 'banana', 'orange', 'mango'], c: [42, 7, 18, 5]},
{a: 2, b: ['apple', 'banana', 'orange', 'mango'], c: [4, 101, 88, 3]},
{a: 3, b: ['apple', 'banana', 'orange', 'mango'], c: [14, 10, 5, 12]},
{a: 4, b: ['apple', 'banana', 'orange', 'mango'], c: [99, 2, 105, 101]}
];
Object.values(arr).forEach(({ b, c }) => {
const fruitValues = c.reduce(
(map, num, i) => map.set(b[i], num),
new Map()
);
c.sort((a, b) => a - b);
b.sort((a, b) => fruitValues.get(a) - fruitValues.get(b));
});
console.log(arr);
You can zip elements of b
and c
together, sort them by the c
element, then unpack them back. With this method, only one sort
is necessary, even if you are sorting multiple lists.
const arr = [
{a: 1, b: ['apple', 'banana', 'orange', 'mango'], c: [42, 7, 18, 5]},
{a: 2, b: ['apple', 'banana', 'orange', 'mango'], c: [4, 101, 88, 3]},
{a: 3, b: ['apple', 'banana', 'orange', 'mango'], c: [14, 10, 5, 12]},
{a: 4, b: ['apple', 'banana', 'orange', 'mango'], c: [99, 2, 105, 101]}
];
Object.values(arr).forEach(row => {
let sorting = row.b.map((e, i, a) => [e, row.c[i]]);
sorting.sort(([b1, c1], [b2, c2]) => c1 - c2);
row.b = sorting.map(([e, ]) => e);
row.c = sorting.map(([, e]) => e);
});
console.log(arr);
I am trying to search some words with special characters in jQuery Datatables plugin. There are some results in datatable like this: Peinado, Alma_María Aguilar Castillo, Antonio José When I try to ...
I am trying to search some words with special characters in jQuery Datatables plugin. There are some results in datatable like this: Peinado, Alma_María Aguilar Castillo, Antonio José When I try to ...
I'm trying to use a recursive function to get the last key value form a simple json using javascript I have this json: { 'a': { 'b': { 'c': 12, 'd': 'Hello World' }, 'e': [...
I'm trying to use a recursive function to get the last key value form a simple json using javascript I have this json: { 'a': { 'b': { 'c': 12, 'd': 'Hello World' }, 'e': [...
I have looked through several threads/resources and can't seem to get working tooltips. Here is the code: nv.addGraph(function() { self.chart = nv.models.multiBarChart() ....
I have looked through several threads/resources and can't seem to get working tooltips. Here is the code: nv.addGraph(function() { self.chart = nv.models.multiBarChart() ....
Here is the Javascript: var bubbles = $('.history .bubble'); bubbles[bubbles.length-1].after('<div class="bubble me">' + text + '</div>'); Here is the HTML: Any idea why anything I ...
Here is the Javascript: var bubbles = $('.history .bubble'); bubbles[bubbles.length-1].after('<div class="bubble me">' + text + '</div>'); Here is the HTML: Any idea why anything I ...