美文网首页JavaScript
js按属性对数组进行排序和分类

js按属性对数组进行排序和分类

作者: Aniugel | 来源:发表于2019-07-21 18:22 被阅读0次

    1、第一步:按age属性进行排序

    var arr = [
            { name: 'zhao', age: 0 },
            { name: 'chen', age: 18 },
            { name: 'sun', age: 8 }
        ];
        function compare(property) {
            return function (a, b) {//倒序的话a b换下位置
                return a[property] - b[property];
            }
        }
        console.log(arr.sort(compare('age')))
    

    2、第二步:按属性分组

     var arr = [];//目标数组
        var foo = ''
        objArr.forEach((obj) => {
            if (foo === obj.age) {
                var lastArr = arr[arr.length - 1].name
                lastArr.push(obj.name)
            } else {
                var newArr = [];
                var newObj = {};
                newObj.age = obj.age;
                newArr.push(obj.name);
                newObj.name = newArr;
                arr.push(newObj)
            }
            foo = obj.age;
        })
        console.log(arr)
    

    相关文章

      网友评论

        本文标题:js按属性对数组进行排序和分类

        本文链接:https://www.haomeiwen.com/subject/eafvlctx.html