js implements data list table (array) up and down function encapsulation and realization idea

Title## js realizes data list table (array) up and down function encapsulation and realization idea

1. First explain the implementation idea:

1. First, determine the parameters needed for the encapsulation method. 1. The array to be processed

2. The target array that needs to be replaced

3. Ascending or descending

2. How to implement ascending and descending order:

1. Ascending order: through two layers of traversal to exchange the target position to achieve ascending order.

2. Descending order: Use the idea of ​​​​ascending order to first reverse (flashback) the original array and the target array, then sort by ascending method, and then perform another reversal (flashback) to get the desired order.

2. Code:

//排序:升序降序
/**
 * 
 * @param {原数组} data 
 * @param {*标杆} sign 
 * @param {*升序/降序} isAdd 
 * @returns 
 */
function ascendingOrder(data, sign, isAdd) {
    
    
    let newData = []//用于存储新的数据
    let index = 0//记录索引
    if (!isAdd) {
    
    //降序就先反转原数组和需要处理的数组
        data = reversal(data)
        sign = reversal(sign)
    }
    sign.map((item, indey) => {
    
    //遍历需处理的数组
        for (let i = index; i < data.length; i++) {
    
    //遍历原数组
            if (item.id === data[i].id) {
    
    //找到目标数据
                if (i !== 0) {
    
    //判断是否是首位
                    newData[i] = data[i - 1]//交换需要更换的位置
                    newData[i - 1] = data[i]
                } else {
    
    //如果是首位就不更改
                    newData[i] = data[i]
                }
                if (indey < sign.length - 1) {
    
    //如果后边还有需要处理的数据就记录索引下一次就从索引位置继续查找
                    index = i + 1//下一次就从替换完的后一位开始
                    data = [...newData, ...data.slice(index)]//原数据需要修改为排序后的数组,这里使用的是扩展运算符(...),考虑兼容性可以使用别的方式进行合并
                    break//本轮的替换完成就可以结束本次循环减少不必要的性能消耗
                }
            } else {
    
    
                newData[i] = data[i]//如果不是目标数组就直接赋值
            }
        }
    })
    if (!isAdd) {
    
    //如果是降序就需要把先前倒叙处理完的数据反转为目标顺序
        newData = reversal(newData)
    }
    return newData //返回结果
}
// 数组反转
function reversal(data) {
    
    
    let newData = []
    for (let index = data.length - 1; index >= 0; index--) {
    
    
        newData.push(data[index]);
    }
    return newData
}

3. Summary

​ There are many methods for ascending and descending order of an array list. First, we must clarify our thinking and then write code to implement it. Do more and more.

Guess you like

Origin blog.csdn.net/weixin_45385944/article/details/126522744