使用数组对对象进行排序,并将值存储在另一个数组中

时间:2018-04-05 20:16:50

标签: javascript arrays angularjs sorting

我有一个带有属性和值的对象参数,如

$scope.chartOptions.response.items.count = { amazing: 8, amenities: 6, awesome: 7, beautiful: 15, better: 9, clean: 12, comfortable: 8, complaint: 6, definitely stay: 6, excellent: 11, friendly: 17, front desk: 8, good: 15, gorgeous: 6, great: 28, helpful: 11, nice: 15, perfect: 7, the best: 10, wonderful: 12 }

该数组的值为20个索引。该数组看起来像

series[] = ["great", "friendly", "good", "beautiful", "nice", "wonderful", "clean", "excellent", "helpful", "the best", "better", "comfortable", "front desk", "amazing", "perfect", "awesome", "amenities", "complaint", "gorgeous", "definitely stay"]

我想根据数组中的值对对象进行排序,并将所有数值存储在第二个数组中,如series2[]= [28, 17, 15...] 这可能是使用angularjs和javascript

1 个答案:

答案 0 :(得分:1)

使用Array.map()迭代series,并使用当前字符串从count获取值:

const count = { amazing: 8, amenities: 6, awesome: 7, beautiful: 15, better: 9, clean: 12, comfortable: 8, complaint: 6, 'definitely stay': 6, excellent: 11, friendly: 17, 'front desk': 8, good: 15, gorgeous: 6, great: 28, helpful: 11, nice: 15, perfect: 7, 'the best': 10, wonderful: 12 };
const series = ["great", "friendly", "good", "beautiful", "nice", "wonderful", "clean", "excellent", "helpful", "the best", "better", "comfortable", "front desk", "amazing", "perfect", "awesome", "amenities", "complaint", "gorgeous", "definitely stay"];


const sortedNumbers = series.map((str) => count[str]);

console.log(sortedNumbers);