Home > Software design >  Sort array and object by values from JSON in js
Sort array and object by values from JSON in js

Time:01-25

Develop a simple application for sorting and selecting data according to predefined criteria rules The application must be able to work with a list of arbitrary JSON object structures, select objects corresponding to keys with corresponding values, and also sort objects by value using the natural sort order. I tried different ways like filter(), map(), sort, and many others... I am a full noob.... example

{"data":[ {"name": "Peter", "email": "[email protected]"}, 
{"name": "Peter", "email": "[email protected]"}, 
{"name": "Marge", "email": "[email protected]"}]}

income values:

{"condition": {"include": [{"name": "Peter"}], "sortBy": ["email"]}}// returns only with name peter

and

"condition": {"exclude": [{"name":"Marge"}], "sort_by": ["email"]}} // returns other 

Actually, I want to understand what and how so if you can explain it will be great. thanks a lot)

const data = [ 
   {"name": "John", "email": "[email protected]"},
   {"name": "John", "email": "[email protected]"},
   {"name": "Jane", "email": "[email protected]"},
   {"name": "Margaret", "email": "[email protected]"}
];

function fullSort (arr, sort_by){
const propComparator = (sort_by) =>
(a, b) => a[sort_by] === b[sort_by] ? 0 : a[sort_by] < b[sort_by] ? -1 : 1; /// working

    console.log("by parametr", data);
    
    function arrayRemove(arr, sort_by) {   
      return data.filter(function(ele){  ///working
        return ele.name != sort_by; 
      });
    }
    console.log(arrayRemove(arr, sort_by))`
    data.sort(propComparator("sort_by"))`
}  
return fullSort(data, "John");

CodePudding user response:

Here is a function that uses the condition data to apply include, exclude and sorting:

function fullSort(data, condition){
    const propComparator = (sort_by) =>
        (a, b) => (a[sort_by] > b[sort_by]) - (a[sort_by] < b[sort_by]);

    if (condition?.include) {
        console.log("include");
        data = data.filter(ele =>
            condition.include.some(obj => 
                Object.entries(obj).every(([key, value]) =>
                    ele[key] === value
                )
            )
        );
    }
    if (condition?.exclude) {
        data = data.filter(ele =>
            !condition.exclude.some(obj => 
                Object.entries(obj).every(([key, value]) =>
                    ele[key] === value
                )
            )
        );
    }
    return data.sort(propComparator(condition.sortBy));
}

const value = {"condition": {"exclude": [{"name": "John"},{"name": "Jane"}], "sortBy": ["email"]}};
const data = [ 
   {"name": "John", "email": "[email protected]"},
   {"name": "John", "email": "[email protected]"},
   {"name": "Jane", "email": "[email protected]"},
   {"name": "Margaret", "email": "[email protected]"}
];

console.log( fullSort(data, value.condition));

  • Related