To ensure readability, this paper uses free translation instead of literal translation.
To read more good articles, please Punch GitHub Blog Hundreds of excellent articles a year are waiting for you!
Normally we sort by numbers or alphabets, but there are some cases where we may need to customize the sort order.
Before that, let's briefly introduce the reduce method:
Syntax: arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])
callback: Performs a function of each value in the array, with four parameters:
Accumulator: The return value of the accumulator cumulative callback; it is the cumulative value returned when the callback was last called, or initialValue (see below).
currentValue: The element in the array being processed.
CurrtIndex (optional): The index of the current element being processed in the array.If initialValue is provided, the starting index number is 0, otherwise it is 1.
Array (optional): an array that calls reduce()
InitialValue (optional): As the value of the first parameter when the callback function is called for the first time.If no initial value is provided, the first element in the array is used.Calling reduce on an empty array without an initial value will result in an error.
rudeuce process description:
When the callback function executes for the first time, accumulator and currentValue have two different values: if initialValue is provided when reduce() is called, accumulator takes initialValue, currentValue takes the first value in the array; if initialValue is not provided, accumulator takes the first value in the array,Value takes the second value in the array.
Back to the original:
As the example below shows, let's make inProgress the first, followed by todo, then done.
const tasks = [ {id:1, title: 'Job A', status: 'done'}, {id:2, title: 'Job B', status: 'inProgress'}, {id:3, title: 'Job C', status: 'todo'}, {id:4, title: 'Job D', status: 'inProgress'}, {id:5, title: 'Job E', status: 'todo'} ]
First create an array in the desired sort order.
const sortBy = ['inProgress', 'todo', 'done']
Use reduce to create a function with an array of parameters and an array key as the final output with an index value such as {inProgress:0, todo:1, done:2}.
const sortByObject = data => data.reduce( (obj,item,index) => ({ ...obj, [item]:index }), {} ) console.log(sortByObject(sortBy)) /* {inProgress: 0, todo: 1, done: 2} */
So, with the sort settings, we can put it together with a reusable function that passes in an array (data), a sortby array, and a sortField so that we know which field to sort on:
const customSort = ({data, sortBy, sortField}) => { const sortByObject = sortBy.reduce( (obj, item, index) => ({ ...obj, [item]: index }), {}) return data.sort((a, b) => sortByObject[a[sortField]] - sortByObject[b[sortField]]) } console.log(customSort({data:tasks, sortBy, sortField: 'status'}))
This allows us to sort in our custom order, but there is also a problem. If there is a different status item in the list (not in our order), there will be a problem.Therefore, to handle this problem, we need to set a default sort field to capture all the items that are not needed in the sort.
const tasksWithDefault = tasks.map(item => ( { ...item, sortStatus: sortBy.includes(item.status) ? item.status:'other' }) )
This pass is the updated sort field, so now you have the correct sort order, and there are items at the bottom of the list with a status of other.
Full code:
const tasks = [ { id: 1, title: "Job A", status: "done" }, { id: 2, title: "Job B", status: "inProgress" }, { id: 3, title: "Job C", status: "todo" }, { id: 3, title: "Job D", status: "onHold" }, { id: 4, title: "Job E", status: "inProgress" }, { id: 5, title: "Job F", status: "todo" } ]; const sortBy = ["inProgress", "todo", "done"]; const customSort = ({ data, sortBy, sortField }) => { const sortByObject = sortBy.reduce( (obj, item, index) => ({ ...obj, [item]: index }), {} ); return data.sort( (a, b) => sortByObject[a[sortField]] - sortByObject[b[sortField]] ); }; const tasksWithDefault = tasks.map(item => ({ ...item, sortStatus: sortBy.includes(item.status) ? item.status : "other" })); console.log( customSort({ data: tasksWithDefault, sortBy: [...sortBy, "other"], sortField: "sortStatus" }) );
Run result:
BUGs that may exist after code deployment are not known in real time. In order to solve these BUGs afterwards, a lot of time has been spent debugging the log. By the way, a useful BUG monitoring tool is recommended. Fundebug.
Original: https://www.youtube.com/watch...
Communication
The dry goods series articles are summarized below, feel good to order Star, welcome to join the group to learn from each other.
https://github.com/qq44924588...
I am Xiao Zhi, the author of the public number "Move the World", a fan of keeping learning about front-end technology.I often share what I've learned and what I've seen. On the way to the next level, I'll reluctantly!
Focus on the public number and reply to the benefits in the background. You can see the benefits, you know.