Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[js] 第29天 写一个获取数组的最大值、最小值的方法 #104

Open
haizhilin2013 opened this issue May 14, 2019 · 30 comments
Open
Labels
js JavaScript

Comments

@haizhilin2013
Copy link
Collaborator

第29天 写一个获取数组的最大值、最小值的方法

@haizhilin2013 haizhilin2013 added the js JavaScript label May 14, 2019
@JamesSky
Copy link

Array.prototype.max = function(){
	return /^\d*$/g.test(a.join('')) ? Math.max(...a) : '请输入正确格式的数组';
};
var arrFirst = [1,'3',4];
var arrSecond = [1,'3','a'];
arrFirst.max();
arrSecond.max();

@git710
Copy link

git710 commented May 15, 2019

Math.max.apply(Array,[25,62,91,78,34,62]) //  91
Math.min.apply(Array,[27,64,90,78,34,62]) // 27

@yxkhaha
Copy link

yxkhaha commented May 15, 2019

    let arr = [10,20];
    let arr2 = arr.sort(function(a,b){
      return b-a;
    });
    document.write(arr2[0]);

@tiu5
Copy link

tiu5 commented May 15, 2019

// 利用 reduce 冒泡排序
const getMax =  arr =>  arr.reduce((acc, val) => acc = acc < val ? val : acc)
getMax([25, 62, 91, 78, 34, 62]) // 91

@tzjoke
Copy link

tzjoke commented May 28, 2019

Array.prototype.max = function() {
    return Math.max.apply(null, this)
}

es6

Math.max(...array)

@myprelude
Copy link

let arr = [1,2,3,4] 
Math.max(...arr)
Math.min(...arr)

@Konata9
Copy link

Konata9 commented Jul 9, 2019

因为我是跳着做的,这题可以说是 Day54 的前置题目了。

const getMinAndMax = arr => ({
  // 数组展开在 ES5 中可以用 apply 代替
  // ES5: Math.min.apply(null, arr)
  min: Math.min(...arr),
  max: Math.max(...arr)
});

console.log(getMinAndMax([1, 2, 3, 4, 5, 6, 7, 8, 9]));
console.log(getMinAndMax([12, 223, 13, 4, 25, 36, 7, 18, 90]));

@wyx2014
Copy link

wyx2014 commented Jul 24, 2019

Array.prototype.max = function () { return /^\d*$/.test(this.join(''))?this.reduce((x1,x2)=>x1 = x1 < x2 ? x2 : x1):'请输入正确格式的数组'; }

@Vi-jay
Copy link

Vi-jay commented Jul 29, 2019

const getMaxFromArr = arr => Math.max(...arr);
const getMinFromArr = arr => Math.min(...arr);

@15190408121
Copy link

Math.max(...array)
Math.min(...array)

@zhangkuibao
Copy link

zhangkuibao commented Sep 10, 2019

ES6之前用apply代替,作用域无所谓
Math.max.apply(null,[1,2,3]);

@gzwgq222
Copy link

// 利用 reduce 冒泡排序
const getMax =  arr =>  arr.reduce((acc, val) => acc = acc < val ? val : acc)
getMax([25, 62, 91, 78, 34, 62]) // 91

这不是冒泡排序吧?

@gzwgq222
Copy link

gzwgq222 commented Sep 10, 2019

  • ES5
Math.max.apply(null, array);
array.sort((a, b) => a - b);
const max = array[array.length - 1],
      min = array[0];

  • ES6
Math.max(...array);
Math.min(...array);
arr.reduce((prev, cur) => Math.max(prev, cur));
arr.reduce((prev, cur) => prev = prev > cur ? prev : cur);

@15190408121
Copy link

封装了一个方法

function Arry(arr) {
	var arrys = {
		max: Math.max.apply(Array, arr),
		min: Math.min.apply(Array, arr)
	};
	return arrys;
}
console.log(Arry([25,62,91,78,34,62]));

@censek
Copy link

censek commented Oct 29, 2019

var arr = [27, 64, 90, 78, 34, 62];
var newArr = arr.sort((a, b) => a - b);

var max = newArr[newArr.length - 1];
var min = newArr[0];


console.log(max);
console.log(min);

@0x3c
Copy link

0x3c commented Mar 5, 2020

function max() {
  return Math.max.apply(null, arguments);
}

function min() {
  return Math.min.apply(null, arguments);
}

@13168335674
Copy link

const getMaxAndMin = (arr=[]) => {
    arr.sort((a,b)=>a-b);
    return {
        max: arr[arr.length-1],
        min: arr[0]
    }
}

@blueRoach
Copy link

let arr = [1, 2, 3, 4, 5, 6]

Math.max.apply(null, arr)
Math.min.apply(null, arr)

Math.max(...arr)
Math.min(...arr)

arr.reduce((a, b) => Math.max(a, b))
arr.reduce((a, b) => Math.min(a, b))

let temp = arr.sort((a, b) => a - b)
temp[temp - 1]
temp[0]

@CoderLeiShuo
Copy link

CoderLeiShuo commented Aug 6, 2020

1. 排序法

首先我们对数组进行排序,可以按照升序排序,也可以按照降序排序。排序之后的数组中的第一个和最后一个元素就是我们需要的最大值或最小值。

排序可以使用sort()方法

// 方法一:排序法
arr.sort(function (a, b) {
    // 升序排序
    return a - b;
})

maxValue = arr[arr.length - 1];
minValue = arr[0];
console.log('最大值为:', maxValue); // 91
console.log('最小值为:', minValue); // 25

2. 假设法

可以假设数组中的第一个值是最大值,然后拿这个最大值和数组中的其他元素逐一比较,如果后面的某一个值比假设的值还大,说明假设错了,我们把假设的值进行替换,将这个值赋假设为新的最大值。循环结束后,拿到的结果就是我们想要的。最小值反之。

// 假设第一个数组元素就是数组中的最大值
maxValue = arr[0];
for (let i = 0; i < arr.length; i++) {
    let cur = arr[i];
    // 如果当前元素的值比假设的最大值大,就设置当前值为最大值,继续和后面元素比较
    maxValue = cur > maxValue ? cur : maxValue;
}
console.log('最大值为:', maxValue);

// 假设第一个数组元素就是数组中的最小值
minValue = arr[0];
for (let i = 0; i < arr.length; i++) {
    let cur = arr[i];
     // 如果当前元素的值比假设的最小值小,就设置当前值为最小值,继续和后面元素比较
    minValue = cur < minValue ? cur : minValue;
}
console.log('最小值为:', minValue);

3. 使用Math对象中的max/min方法

Math.max()函数返回一组数中的最大值,例如:

console.log(Math.max(1, 3, 2)); // 3

但是这个函数并不接受数组作为参数,且这个函数也不是数组对象中的方法,无法通过数组直接调用。这里我们可以使用apply来实现求数组中的最值,因为apply()方法接收的函数参数刚好是以数组方式进行传入的。

// 使用apply方法,可以直接将数组作用参数传入
maxValue = Math.max.apply(null, arr);
minValue = Math.min.apply(null, arr);

console.log('最大值为:', maxValue); // 91
console.log('最小值为:', minValue); // 25

一个小问题:

为什么通过apply就可以实现数组求最值了呢?

看一下applythis参数,上面代码中传递了一个null,也就是并没有将Math.max()方法绑定到其他对象上。这里只涉及到了两点:

  • Math.max()需要传入的是多个数值
  • apply()只需要把接收到的多个参数传递给Math.max(),只不过接收的多个参数是以数组形式接收的,刚好可以把数组传入,从而实现数组求最值。在apply()方法内部再将数组中的元素拆分成一个一个的参数值,传递给Math.max()即可。

4. 使用ES6的扩展运算符

扩展运算符可以展开数组,代替apply()将数组转化成函数参数的需求。

例如:

function sum(x, y, z) {
    return x + y + z;
}

const numbers = [1, 2, 3];

console.log(sum(...numbers)); // 6

那么正好可以使用这个运算符将数组展开,展开成多个数值,然后作为多个参数向Math.max()传入。

console.log('最大值为:', Math.max(...arr)); // 91
console.log('最小值为:', Math.min(...arr)); // 25

参考文章

@laboonly
Copy link


const arr = [1,2,3,4,5,6,7,8]

//调用数学方法
function max(arr) {
    return Math.max.apply(null,arr);
}

function min(arr) {
    return Math.min.apply(null,arr);
}

// 循环对比
function max2(arr) {
    let res = -Infinity;
    for(i of arr) {
        if(res <= i) {
           res = i
        }
    }
    return res;
}

//排序然后取值 arr[0] arr[arr.length - 1]
arr.sort(function(a,b){
    return a-b;
})








@smile-2008
Copy link

Math.max.apply(Array,[25,62,91,78,34,62]) // 91
Math.min.apply(Array,[27,64,90,78,34,62]) // 27

@maxthonl
Copy link

maxthonl commented Oct 28, 2020

Math.max 和 Math.min 虽然能实现, 但是如果这道题目希望的是同时获取最大值和最小值,应该是没有捷径的,以数组的第一个元素作为参照值遍历一遍的时间复杂度是n,另外如果用排序实现,显然是不合理的。

@Honjaychang
Copy link

看了评论 自己居然没想到Math.max
但是昨天看题时发现一个数组的去重(考虑多维数组) 利用Array.prototype.flat()
所以我就想到了下面这个方法

function get(nums) {
  nums = nums.flat(Infinity).sort((a, b) => a - b)//[ 1, 1, 2, 2, 4, 5 ]
  return [nums[0], nums[nums.length - 1]]
}

console.log(get([1, 2, [5, 4, [2, 1]]]))//[ 1, 5 ]

@github-cxtan
Copy link

console.log(Math.max(...array));
console.log(Math.min(...array));

@xiaoqiangz
Copy link

// 获取数组最大值 最小值
let arr8 = [2,3,44,3,55,31,23]
function mathMethod(arr) {
console.log(Math.min.apply(null, arr))
console.log(Math.max.apply(null, arr))
return 最小值:${Math.min(...arr)} ---最大值: ${Math.max(...arr)}
}
console.log(mathMethod(arr8))

@wenxd
Copy link

wenxd commented Jun 6, 2022

let arr = [2, 4, 6, 8, 1, 23, 12, 2, 44, 6, 865, 4, 2, 5, 6, 7, 89, 87]
  let min, max
  for (let index = 0; index < arr.length; index++) {
    if (index === 0) {
      min = max = arr[index];
    } else {
      if (arr[index] > max) {
        max = arr[index];
      }
      if (arr[index] < min) {
        min = arr[index]
      }
    }
  }
  console.log(min,max);

@wyy-g
Copy link

wyy-g commented Sep 16, 2022

function getMaxMin(arr){
    let newArr = arr.sort((a, b) => {
         return a - b;
    })
    return {
        Max:  newArr[newArr.length - 1],
        Min: newArr[0];
    }
}

@CoderLeiShuo
Copy link

CoderLeiShuo commented Sep 16, 2022 via email

@never123450
Copy link

在JavaScript中,可以使用以下方法来获取数组的最大值和最小值:

1. 使用Math对象的max()和min()方法:
const array = [1, 5, 3, 2, 4];
   const max = Math.max(...array);
   const min = Math.min(...array);
   console.log(max); // 输出最大值
   console.log(min); // 输出最小值
2. 使用reduce()方法:
const array = [1, 5, 3, 2, 4];
   const max = array.reduce((a, b) => Math.max(a, b));
   const min = array.reduce((a, b) => Math.min(a, b));
   console.log(max); // 输出最大值
   console.log(min); // 输出最小值
3. 使用循环遍历数组:
const array = [1, 5, 3, 2, 4];
   let max = array[0];
   let min = array[0];
   for (let i = 1; i < array.length; i++) {
     if (array[i] > max) {
       max = array[i];
     }
     if (array[i] < min) {
       min = array[i];
     }
   }

console.log(max); // 输出最大值
console.log(min); // 输出最小值
以上三种方法都可以获取数组的最大值和最小值。根据具体的情况和需求,选择适合的方法来处理数组。

@never123450
Copy link

never123450 commented Sep 5, 2023

在JavaScript中,可以使用以下方法来获取数组的最大值和最小值:

1. 使用Math对象的max()和min()方法:
const array = [1, 5, 3, 2, 4];
   const max = Math.max(...array);
   const min = Math.min(...array);
   console.log(max); // 输出最大值
   console.log(min); // 输出最小值
2. 使用reduce()方法:
const array = [1, 5, 3, 2, 4];
   const max = array.reduce((a, b) => Math.max(a, b));
   const min = array.reduce((a, b) => Math.min(a, b));
   console.log(max); // 输出最大值
   console.log(min); // 输出最小值
3. 使用循环遍历数组:
const array = [1, 5, 3, 2, 4];
   let max = array[0];
   let min = array[0];
   for (let i = 1; i < array.length; i++) {
     if (array[i] > max) {
       max = array[i];
     }
     if (array[i] < min) {
       min = array[i];
     }
   }

   console.log(max); // 输出最大值
   console.log(min); // 输出最小值

以上三种方法都可以获取数组的最大值和最小值。根据具体的情况和需求,选择适合的方法来处理数组。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
js JavaScript
Projects
None yet
Development

No branches or pull requests