按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' ]