按对象属性值对数组进行排序,该属性值与第二个数组中的字符串相同 [英] Sort an array by object property value same as string in second array

查看:94
本文介绍了按对象属性值对数组进行排序,该属性值与第二个数组中的字符串相同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对不起,标题,我真的不知道该怎么写。我被困住了,我需要按照其对象的title属性值将数组排序为第二个字符串数组的顺序。

Sorry about the title, I'm really not sure how to word this. I'm stuck, I need to sort an array by its object's title property value, into the same order of a second array of strings.

基本上,我有两个数组...

Basically, I have two arrays...

var titles = [
  'title1',
  'title2',
  'title3',
  'title4',
  'title5'
]

var objects = [
  {
    title: 'title5',
    ...//other values
  }, {
    title: 'title3',
    ...//other values
  }
  , {
    title: 'title4',
    ...//other values
  }, {
    title: 'title1',
    ...//other values
  }, {
    title: 'title2',
    ...//other values
  } 
]

我想按与<$ c $中的字符串相同的顺序对对象数组进行排序c> titles 数组。这可能吗?我的代码库可以访问_underscore,也可以使用普通的ES6。

I want to order the objects array in the same order as the strings in titles array. Is this possible? My code base has access to _underscore, or I can use plain ES6.

推荐答案

您可以从titles数组创建对象并将其用于排序对象数组。

You could create object from titles array and use it for ordering your array of objects.

var objects = [{"title":"title5"},{"title":"title3"},{"title":"title4"},{"title":"title1"},{"title":"title2"}]
var titles = ['title1','title2','title3','title4','title5'].reduce((r, e, i) => Object.assign(r, {[e]: i}), {})

objects.sort((a, b) => titles[a.title] - titles[b.title])
console.log(objects)

这篇关于按对象属性值对数组进行排序,该属性值与第二个数组中的字符串相同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆