Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/412.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
按属性对列表排序,并在JavaScript中的每个第一个字母更改之前添加一个对象_Javascript_Arrays_Sorting_Ecmascript 6 - Fatal编程技术网

按属性对列表排序,并在JavaScript中的每个第一个字母更改之前添加一个对象

按属性对列表排序,并在JavaScript中的每个第一个字母更改之前添加一个对象,javascript,arrays,sorting,ecmascript-6,Javascript,Arrays,Sorting,Ecmascript 6,因此,我尝试制作一个如下的UI: let final = [] // sort by first letter const sortedUsers = state.test_list.sort((a, b) => a.name.localeCompare(b.name)) for (let x = 0; x < sortedUsers.length; x++) { const user = sortedUsers[x].name

因此,我尝试制作一个如下的UI:

    let final = []
    // sort by first letter
    const sortedUsers = state.test_list.sort((a, b) => a.name.localeCompare(b.name))
    for (let x = 0; x < sortedUsers.length; x++) {
        const user = sortedUsers[x].name
        if (user.charAt(0) === 'A') {
            const checkIfExists = final.findIndex((f) => f.header === 'A')
            // add the header A if it doesn't exist
            if (checkIfExists < 0) final.push({header: 'A'})
        }
        else if (user.charAt(0) === 'B') {
            const checkIfExists = final.findIndex((f) => f.header === 'B')
            // add the header B if it doesn't exist
            if (checkIfExists < 0) final.push({header: 'B'})
        }
        // else if up to the letter Z
        final.push(user)
    }

我有一系列的用户

[{name: 'Julia'}, {name: 'Ismeh'}, {name: 'Alison'}, {name: 'Andrea'}, {name: 'Betty'}]
我试图做的是按照name属性的第一个字母对数组进行排序,并在每个数组之前添加一个header对象。例如,在图中,您可以看到字母A、B、I和J作为标题

现在,我让它像这样工作:

    let final = []
    // sort by first letter
    const sortedUsers = state.test_list.sort((a, b) => a.name.localeCompare(b.name))
    for (let x = 0; x < sortedUsers.length; x++) {
        const user = sortedUsers[x].name
        if (user.charAt(0) === 'A') {
            const checkIfExists = final.findIndex((f) => f.header === 'A')
            // add the header A if it doesn't exist
            if (checkIfExists < 0) final.push({header: 'A'})
        }
        else if (user.charAt(0) === 'B') {
            const checkIfExists = final.findIndex((f) => f.header === 'B')
            // add the header B if it doesn't exist
            if (checkIfExists < 0) final.push({header: 'B'})
        }
        // else if up to the letter Z
        final.push(user)
    }
let final=[]
//按首字母排序
const sortedUsers=state.test_list.sort((a,b)=>a.name.localeCompare(b.name))
对于(设x=0;xf.header=='A')
//如果标题A不存在,则添加标题A
if(checkIfExists<0)final.push({header:'A'})
}
else if(user.charAt(0)==“B”){
const checkIfExists=final.findIndex((f)=>f.header=='B')
//如果标题B不存在,则添加标题B
if(checkIfExists<0)final.push({header:'B'})
}
//否则,如果达到字母Z
final.push(用户)
}
如果我记录最后一个数组,我会得到:

这是正确的

我担心的是代码很长,我不知道它是否可以优化或使代码更小


这样做还有其他选择吗?如果有任何帮助,我们将不胜感激。

为什么不创建一个名称集合,按第一个字母分组?然后,您可以在其上循环,并创建列表。用于创建分组的集合

然后使用迭代分组集合并呈现结果:

let数据=[{
名字:“朱莉娅”
}, {
姓名:“Ismeh”
}, {
姓名:“艾莉森”
}, {
名字:“安德里亚”
}, {
名字:“贝蒂”
}];
让合并=数据。减少((结果,项目)=>{
let letter=item.name[0]。toUpperCase();
如果(!结果[字母]){
结果[字母]=[];
}
结果[字母]。推送(项目);
返回结果;
}, {});
控制台日志(组合);
//迭代结果
Object.key(组合).forEach(key=>{
//密钥将是用户名和密码的第一个字母
//组合的[key]将是一个用户对象数组
console.log(键,组合[key]);

});非常简单,请尝试对它们进行排序,然后使用
。reduce

const unsortedPeople=[{name:'Julia'},{name:'Ismeh'},{name:'Alison'},{name:'Andrea'},{name:'Betty'}];
const sortedUsers=unsortedPeople.sort((a,b)=>a.name.localeCompare(b.name))
const final=分拣机。reduce((最终分拣机,用户)=>{
const thisUserFirstChar=user.name[0];
如果(finalSoFar.length==0)addHeader();
否则{
const lastUserFirstChar=finalSoFar[finalSoFar.length-1]。名称[0];
if(lastUserFirstChar!==thisUserFirstChar)addHeader();
}
最终自动推送(用户);
返回终场;
函数addHeader(){
finalSoFar.push({header:thisUserFirstChar});
}
}, []);

控制台日志(最终)为什么不在循环时跟踪当前缩写。然后,可以在头部发生更改时添加头部:

var users=[{name:'Julia'},{name:'Ismeh'},{name:'Alison'},{name:'Andrea'},{name:'Betty'}]
const sortedUsers=users.sort((a,b)=>a.name.localeCompare(b.name))
var currentHeader
let final=分拣机。减少((a,用户)=>{
if(currentHeader!==用户名[0]){
currentHeader=user.name[0]
a、 推送({header:currentHeader})
}
a、 推送(用户)
归还
},[])

console.log(最终版)
这里有一种方法:

const users=[{name:'Julia'},{name:'Ismeh'},{name:'Alison'},{name:'Andrea'},{name:'Betty'}];
让最后一个索引;
让结果=[];
users.sort((a,b)=>{
返回a.name>b.name;
}).forEach((用户)=>{
常量索引=user.name.charAt(0);
如果(索引!==lastIndex){
结果:推({
标题:索引
});
}
lastIndex=指数;
结果推送(user.name);
}, []);
控制台日志(结果)您可以使用lodash的名称和方法

  • 这个orderBy类似于u.sortBy,只是它允许指定要排序的迭代对象的排序顺序。如果未指定顺序,则所有值都按升序排序。否则,请为相应值的降序指定“desc”,或为升序指定“asc”
  • groupBy将创建一个对象,该对象由通过iteratee运行集合的每个元素的结果生成的键组成。分组值的顺序由它们在集合中出现的顺序决定。每个键的对应值是负责生成键的元素数组。使用一个参数(value)调用iteratee
范例

// The `_.property` iteratee shorthand.
_.groupBy(['one', 'two', 'three'], 'length');
// => { '3': ['one', 'two'], '5': ['three'] }

// Sort by `user` in ascending order and by `age` in descending order.
_.orderBy(users, ['user', 'age'], ['asc', 'desc']);
含氯

让myArr=[{
名字:“朱莉娅”
}, {
姓名:“Ismeh”
}, {
名字:“安德里亚”
}, {
姓名:“艾莉森”
}, {
名字:“贝蒂”
}];
myArr=..orderBy(myArr,['name'],['asc']);
设r=u.groupBy(myArr,o=>{
返回o.name.charAt(0.toUpperCase();
})
控制台日志(r)

太棒了!这是我一直在寻找的东西。这看起来也很棒。我也会试试这个。这对我来说是一个很好的锻炼