How do I classify my object array versus my table?

I want to change the order of the object array, I want it (const quote) to denote the position of the theme (const themeOrder).

const quote = [{
  theme: 'spirituality'
}, {
  theme: 'politic'
}, {
  theme: 'military'
}, {
  theme: 'politic'
}, {
  theme: 'tech'
}];
const themeOrder = ['tech', 'politic', 'military', 'spirituality'];

      

I want a result like

newQuote = [{
  theme: 'tech'
}, {
  theme: 'politic'
}, {
  theme: 'military'
}, {
  theme: 'spirituality'
}]

      

+3


source to share


4 answers


Just sort()

elements based on their index in themeOrder

:

quote.sort((x,y) => themeOrder.indexOf(x.theme) > themeOrder.indexOf(y.theme) ? 1 : -1))

      



See Documentation

+3


source


You can sort the array objects with by Array.prototype.sort

comparing the index positions of the theme

properties in the array themeOrder

:



const quote = [{
  theme: 'spirituality'
}, {
  theme: 'politic'
}, {
  theme: 'military'
}, {
  theme: 'politic'
}, {
  theme: 'tech'
}];
const themeOrder = ['tech', 'politic', 'military', 'spirituality'];

quote.sort((a, b) => themeOrder.indexOf(a.theme) - themeOrder.indexOf(b.theme));

console.log(quote);
      

Run codeHide result


+1


source


Use Map to create topic / order (index) key / value pairs. When you sort, translate topic names into index numbers and sort by those values.

const quote = [{
  theme: 'spirituality'
}, {
  theme: 'politic'
}, {
  theme: 'military'
}, {
  theme: 'politic'
}, {
  theme: 'tech'
}];

const themeOrder = ['tech', 'politic', 'military', 'spirituality'];
const order = themeOrder.reduce((map, key, index) => map.set(key, index), new Map());

quote.sort((a, b) => order.get(a.theme) - order.get(b.theme));

console.log(quote);
      

Run codeHide result


0


source


To sort an array of objects, you can use:

quotes.sort(function(a,b) {
   return (a.theme > b.theme) ? 1 : ((b.theme > a.theme) ? -1 : 0);
});

      

-1


source







All Articles