# 将数组中的名称按升序排序

2023-08-24 17:34:59

## 3 回答

TA贡献1820条经验 获得超9个赞

.map方向是正确的。您需要将数据转换为字符串，然后对它们进行排序。

let people = [

[

['firstName', 'Rachel'],

['age', 10],

['gender', 'female'],

],

[

['firstName', 'Sam'],

['lastName', 'Smith'],

['age', 20],

['gender', 'male'],

],

];

function nameInOrder(arr) {

return arr.map(person => {

const fields = person.map(entry => entry[0])

if (fields.includes('firstName') && fields.includes('lastName')) {

return [

person.find(entry => entry[0] == 'firstName')[1],

person.find(entry => entry[0] == 'lastName')[1],

].join(' ')

} else if (fields.includes('firstName')) {

return person.find(entry => entry[0] == 'firstName')[1]

} else if (fields.includes('lastName')) {

return person.find(entry => entry[1] == 'lastName')[1]

} else {

return ''

}

}).sort()

}

console.log(nameInOrder(people))

TA贡献1789条经验 获得超8个赞

names.sort((a,b) => {

var nameA = a[0][1].toUpperCase(); // ignore upper and lowercase

var nameB = b[0][1].toUpperCase(); // ignore upper and lowercase

if (nameA < nameB) {

return -1;

}

if (nameA > nameB) {

return 1;

}

// names must be equal

return 0;

});

let names = [

[

{ 'firstName': 'Rachel' },

{ 'age': 10 },

{ 'gender': 'female' }

]

];

names.sort((a,b) => {

var nameA = a.firstName.toUpperCase(); // ignore upper and lowercase

var nameB = b.firstName.toUpperCase(); // ignore upper and lowercase

if (nameA < nameB) {

return -1;

}

if (nameA > nameB) {

return 1;

}

// names must be equal

return 0;

});

TA贡献1799条经验 获得超8个赞

const names = [

[

['firstName', 'Rachel'],

['age', 10],

['gender', 'female'],

],

[

['firstName', 'Sam'],

['lastName', 'Smith'],

['age', 20],

['gender', 'male'],

],

];

const result = names.map(person => {

const name = person.reduce((obj, [index, value]) => {

obj[index] = value;

return obj;

}, {});

return `\${name.firstName || ''} \${name.lastName || ''}`.trim();

});

console.log (result);

• 3 回答
• 0 关注
• 118 浏览

0/150