按 JavaScript 中数组的索引来排序
假设我们有以下对象数组 -
const arr = [
{
'name' : 'd',
'index' : 3
},
{
'name' : 'c',
'index' : 2
},
{
'name' : 'a',
'index' : 0
},
{
'name' : 'b',
'index' : 1
}
];我们需要编写一个 JavaScript 函数,该函数采用一个这样的数组。
该函数应按对象的 index 属性对该数组按升序排序。
然后,该函数应将排序后的数组映射到一个字符串数组,其中每个字符串都是对象 name 属性值对应的值。
因此,对于上述数组,最终输出应如下所示 -
const output = ["a", "b", "c", "d"];
示例
相应的代码为 -
const arr = [
{
'name' : 'd',
'index' : 3
},
{
'name' : 'c',
'index' : 2
},
{
'name' : 'a',
'index' : 0
},
{
'name' : 'b',
'index' : 1
}
];
const sortAndMap = (arr = []) => {
const copy = arr.slice();
const sorter = (a, b) => {
return a['index'] - b['index'];
};
copy.sort(sorter);
const res = copy.map(({name, index}) => {
return name;
});
return res;
};
console.log(sortAndMap(arr));输出
控制台中的输出为 -
[ 'a', 'b', 'c', 'd' ]
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP