js gets the maximum and minimum values and corresponding index values in the array

1. Use es6 (destructuring of arrays, indexOf (method))

getIndexMAx = (arr) => {
    const maxNum = Math.max(...arr)
    const minNum = Math.min(...arr)
    const [maxIndex, minIndex] = [arr.indexOf(maxNum), arr.indexOf(minNum)]
    console.log(maxNum, minNum, maxIndex, minIndex)
}

2. Use native Js to realize this function, mainly through loops 

getMaxMin = (data, key) => {
    if (!data) {
        return false
    }
    let maxIndex = 0
    let minIndex = 0
    let maxNum = data[0][key] || 0
    let minNum = (data[0][key] && data[0][key] !== 0) ? Infinity : data[0][key]
    data.forEach((item, index) => {
        if (item[key] >= maxNum && item[key] !== undefined) {
            maxNum = item[key]
            maxIndex = index
        }
        if (item[key] <= minNum && item[key] !== undefined) {
            minNum = item[key]
            minIndex = index
        }
    })
    console.log(maxNum, minNum, maxIndex, minIndex)
}

Guess you like

Origin blog.csdn.net/hyupeng1006/article/details/125082088