按JavaScript中数组的索引排序
假设我们有以下对象数组-
const arr = [
{
'name' : 'd',
'index' : 3
},
{
'name' : 'c',
'index' : 2
},
{
'name' : 'a',
'index' : 0
},
{
'name' : 'b',
'index' : 1
}
];我们需要编写一个包含一个这样的数组的JavaScript函数。
函数应根据对象的index属性以升序对数组进行排序。
然后,该函数应将排序后的数组映射到字符串数组,其中每个字符串都是对象的相应名称属性值。
因此,对于上述数组,最终输出应类似于-
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' ]
热门推荐
6 保研的祝福语简短
10 年轻20岁祝福语简短
11 朋友结婚祝福语信息简短
12 女孩婚礼贺卡祝福语简短
13 30段点歌简短祝福语
14 虎年春节祝福语图文简短
15 写给后妈祝福语大全简短
16 简短回复生日祝福语
17 校长送毕业祝福语简短
18 毕业立体贺卡祝福语简短