0
点赞
收藏
分享

微信扫一扫

JavaScript根据字符串末尾值分组并排序、isArray、throw、TypeError

mafa1993 2022-04-21 阅读 43
function groupingSorting(list) {
    if (!Array.isArray(list)) throw new TypeError(`list is not a Array`);
    if (list.length <= 0) throw new TypeError(`list length cannot be equal to 0`);

    let grouping1 = [],
        grouping2 = [],
        grouping3 = [],
        grouping4 = [],
        grouping5 = [];

    list.forEach(item => {
        let title = item.title,
            str2 = title.substring(title.length - 2),
            str3 = title.substring(title.length - 3);

        if (str2 === '公司' && str3 !== '分公司') {
            grouping1.push(item);
        } else if (str3 === '分公司' && str2 === '公司') {
            grouping2.push(item);
        } else if (str2 == '部门') {
            grouping3.push(item);
        } else if (str2 === '半晨') {
            grouping4.push(item);
        } else {
            grouping5.push(item);
        }
    });

    return [...grouping1, ...grouping2, ...grouping3, ...grouping4, ...grouping5];
}

// 源数据
let list = [
    { id: 1, title: '1xxx公司' },
    { id: 2, title: '2xxx分公司' },
    { id: 3, title: '3xxx公司' },
    { id: 4, title: '4xxx部门' },
    { id: 5, title: '5xxx分公司' },
    { id: 6, title: '6xxx部门' },
    { id: 7, title: '7xxx' },
    { id: 8, title: '8xxx半晨' },
    { id: 9, title: '9xxx舒冬' },
    { id: 10, title: '10xxx半晨' },
    { id: 11, title: '11xxx李清照' },
    { id: 12, title: '12xxx李白' },
];

console.log(groupingSorting(list));
// (12) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
举报

相关推荐

0 条评论