Programing

Javascript의 배열에서 가장 작은 값을 얻습니까?

lottogame 2021. 1. 9. 09:17
반응형

Javascript의 배열에서 가장 작은 값을 얻습니까?


배열 justPrices에는 다음과 같은 값이 있습니다.

[0] = 1.5
[1] = 4.5
[2] = 9.9.

배열에서 가장 작은 값을 어떻게 반환합니까?


Jon Resig는 이 기사 에서 Array 프로토 타입을 확장하고 안타깝게도 배열이 아닌 가변 개수의 인수 를 사용하는 기본 Math.min 메서드를 호출하여이를 달성 할 수있는 방법을 설명했습니다 .

Array.min = function( array ){
    return Math.min.apply( Math, array );
};

그리고:

var minimum = Array.min(array);

최소값을 찾는 가장 간결한 코드는 아마도 나머지 매개 변수 일 것입니다 .

const arr = [14, 58, 20, 77, 66, 82, 42, 67, 42, 4]
const min = Math.min(...arr)
console.log(min)


나머지 매개 변수는 기본적으로 Function.prototype.apply함수의 컨텍스트를 변경할 필요가 없을 때 편리한 속기입니다 .

var arr = [14, 58, 20, 77, 66, 82, 42, 67, 42, 4]
var min = Math.min.apply(Math, arr)
console.log(min)


이것은 또한 다음에 대한 훌륭한 사용 사례입니다 Array.prototype.reduce.

const arr = [14, 58, 20, 77, 66, 82, 42, 67, 42, 4]
const min = arr.reduce((a, b) => Math.min(a, b))
console.log(min)

Math.min직접 전달하고 싶을 수 reduce있지만 콜백은 추가 매개 변수를받습니다.

callback (accumulator, currentValue, currentIndex, array)

이 특별한 경우에는 약간 장황 할 수 있습니다. reduce단일 값으로 집계하려는 복잡한 데이터 모음이있는 경우 특히 유용합니다.

const arr = [{name: 'Location 1', distance: 14}, {name: 'Location 2', distance: 58}, {name: 'Location 3', distance: 20}, {name: 'Location 4', distance: 77}, {name: 'Location 5', distance: 66}, {name: 'Location 6', distance: 82}, {name: 'Location 7', distance: 42}, {name: 'Location 8', distance: 67}, {name: 'Location 9', distance: 42}, {name: 'Location 10', distance: 4}]
const closest = arr.reduce(
  (acc, loc) =>
    acc.distance < loc.distance
      ? acc
      : loc
)
console.log(closest)


물론 항상 클래식 반복을 사용할 수 있습니다.

var arr,
  i,
  l,
  min

arr = [14, 58, 20, 77, 66, 82, 42, 67, 42, 4]
min = Number.POSITIVE_INFINITY
for (i = 0, l = arr.length; i < l; i++) {
  min = Math.min(min, arr[i])
}
console.log(min)

... 그러나 고전적인 반복조차도 현대적인 변화를 가져올 수 있습니다.

const arr = [14, 58, 20, 77, 66, 82, 42, 67, 42, 4]
let min = Number.POSITIVE_INFINITY
for (const value of arr) {
  min = Math.min(min, value)
}
console.log(min)


배열의 가장 작은 값을 반환하는 가장 쉬운 방법은 Math.min () 함수에서 Spread Operator를 사용하는 것입니다.

return Math.min(...justPrices);
//returns 1.5 on example given 

MDN의 페이지는이를 더 잘 이해하는 데 도움이됩니다 : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/min

추가 사항 : 이것은 Math.max () 함수에서도 작동합니다.

return Math.max (... justPrices); // 주어진 예제에서 9.9를 반환합니다.

도움이 되었기를 바랍니다!


업데이트 : Darin의 / John Resig 대답을 사용하십시오 . thisArg를 지정할 필요가 min없으므로 Math.min.apply(null, arr)잘 작동합니다.


또는 배열을 정렬 하고 값 # 1을 얻을 수 있습니다 .[2,6,7,4,1].sort()[0]

[!] 그러나 사용자 정의 숫자 정렬 기능을 제공하지 않으면 이것은 매우 제한된 경우에만 작동합니다 : 10 미만의 양수 . 어떻게 깨지는 지보십시오 :

var a = ['', -0.1, -2, -Infinity, Infinity, 0, 0.01, 2, 2.0, 2.01, 11, 1, 1e-10, NaN];

// correct: 
a.sort( function (a,b) { return a === b ? 0 : a < b ? -1: 1} );
//Array [NaN, -Infinity, -2, -0.1, 0, "", 1e-10, 0.01, 1, 2, 2, 2.01, 11, Infinity]

// incorrect:
a.sort();
//Array ["", -0.1, -2, -Infinity, 0, 0.01, 1, 11, 1e-10, 2, 2, 2.01, Infinity, NaN]

또한 배열이 제자리에서 변경되어 원하는 것이 아닐 수도 있습니다.


이 배열이 있다고 상상해보십시오.

var arr = [1, 2, 3];

ES6 방법 :

var min = Math.min(...arr); //min=1

ES5 방법 :

var min = Math.min.apply(null, arr); //min=1

D3.js를 사용하는 경우 동일한 기능을 수행하지만 정의되지 않은을 무시 하고 자연 순서도 확인 하는 편리한 함수가 있습니다.

d3.max (배열 [, 접근 자])

자연 순서를 사용하여 주어진 배열의 최대 값을 반환합니다. 배열이 비어 있으면 undefined를 반환합니다. 선택적 접근 자 함수를 지정할 수 있으며 이는 최대 값을 계산하기 전에 array.map (accessor)를 호출하는 것과 같습니다.

기본 제공 Math.max와 달리이 메서드는 정의되지 않은 값을 무시합니다. 누락 된 데이터를 무시하는 데 유용합니다. 또한 요소는 숫자 순서가 아닌 자연 순서를 사용하여 비교됩니다. 예를 들어 문자열 [ "20", "3"]의 최대 값은 "3"이고 숫자 [20, 3]의 최대 값은 20입니다.

다음은 D3 v4의 소스 코드입니다.

export default function(values, valueof) {
  var n = values.length,
      i = -1,
      value,
      max;

  if (valueof == null) {
    while (++i < n) { // Find the first comparable value.
      if ((value = values[i]) != null && value >= value) {
        max = value;
        while (++i < n) { // Compare the remaining values.
          if ((value = values[i]) != null && value > max) {
            max = value;
          }
        }
      }
    }
  }

  else {
    while (++i < n) { // Find the first comparable value.
      if ((value = valueof(values[i], i, values)) != null && value >= value) {
        max = value;
        while (++i < n) { // Compare the remaining values.
          if ((value = valueof(values[i], i, values)) != null && value > max) {
            max = value;
          }
        }
      }
    }
  }

  return max;
}

ES6는 미래의 길입니다.

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

다른 사용 사례에 대해 쉽게 일반화되기 때문에이 양식을 선호합니다.


더 쉬운 방법일까요?

justPrices가 가치 측면에서 뒤섞여있어 가장 작은 가치가 어디에 있는지 알 수 없다고 가정 해 보겠습니다.

justPrices[0] = 4.5
justPrices[1] = 9.9
justPrices[2] = 1.5

정렬을 사용하십시오.

justPrices.sort();

It would then put them in order for you. (Can also be done alphabetically.) The array then would be put in ascending order.

justPrices[0] = 1.5
justPrices[1] = 4.5
justPrices[2] = 9.9

You can then easily grab by the first index.

justPrices[0]

I find this is a bit more useful than what's proposed above because what if you need the lowest 3 numbers as an example? You can also switch which order they're arranged, more info at http://www.w3schools.com/jsref/jsref_sort.asp


var array =[2,3,1,9,8];
var minvalue = array[0]; 
for (var i = 0; i < array.length; i++) {
    if(array[i]<minvalue)
    {
        minvalue = array[i];
    }

}
  console.log(minvalue);

function smallest(){
  if(arguments[0] instanceof Array)
    arguments = arguments[0];

  return Math.min.apply( Math, arguments );
}
function largest(){
  if(arguments[0] instanceof Array)
    arguments = arguments[0];

  return Math.max.apply( Math, arguments );
}
var min = smallest(10, 11, 12, 13);
var max = largest([10, 11, 12, 13]);

console.log("Smallest: "+ min +", Largest: "+ max);


If you are using Underscore or Lodash you can get the minimal value using this kind of simple functional pipeline

_.chain([7, 6, -1, 3, 2]).sortBy().first().value()
// -1

You also have the .min function

_.min([7, 6, -1, 3, 2])
// -1

I think I have an easy-to-understand solution for this, using only the basics of javaScript.

function myFunction() {
            var i = 0;
            var smallestNumber = justPrices[0];
            for(i = 0; i < justPrices.length; i++) {
                if(justPrices[i] < smallestNumber) {
                    smallestNumber = justPrices[i];
                }
            }
            return smallestNumber;
        }

The variable smallestNumber is set to the first element of justPrices, and the for loop loops through the array (I'm just assuming that you know how a for loop works; if not, look it up). If an element of the array is smaller than the current smallestNumber (which at first is the first element), it will replace it's value. When the whole array has gone through the loop, smallestNumber will contain the smallest number in the array.


Here is code that will detect the lowest value in an array of numbers.

//function for finding smallest value in an array
function arrayMin(array){
    var min = array[0];
    for(var i = 0; i < array.length; i++){
        if(min < array[i]){
            min = min;
        }else if (min > array[i]){
            min = array[i + 1];
        }else if (min == array[i]){
            min = min;
        }
    }
    return min;
};

call it in this way:

var fooArray = [1,10,5,2];
var foo = arrayMin(fooArray);

(Just change the second else if result from: min = min to min = array[i] if you want numbers which reach the smallest value to replace the original number.)


Here is a recursive way on how to do it using ternary operators both for the recursion and decision whether you came across a min number or not.

const findMin = (arr, min, i) => arr.length === i ? min :
  findMin(arr, min = arr[i] < min ? arr[i] : min, ++i)

Code snippet:

const findMin = (arr, min, i) => arr.length === i ? min :
  findMin(arr, min = arr[i] < min ? arr[i] : min, ++i)
  
const arr = [5, 34, 2, 1, 6, 7, 9, 3];
const min = findMin(arr, arr[0], 0)
console.log(min);

ReferenceURL : https://stackoverflow.com/questions/8934877/obtain-smallest-value-from-array-in-javascript

반응형