-
温温酱
.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))
-
SMILET
您可以使用.sort():定义一个函数来比较您传递给的名称.sort()。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;});
-
函数式编程
如果源数据真的只能是数组。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);