javascript 在javascript中从数组中查找中值(8个值或9个值)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25305640/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 04:20:46  来源:igfitidea点击:

find median values from array in javascript (8 values or 9 values)

javascriptjqueryarrays

提问by Alnitak

How can i find median values from array in javascript

我如何在javascript中从数组中找到中值

this is my array

这是我的阵列

var data = [       
    { values: 4 }, 
    { values: 4 }, 
    { values: 4 }, 
    { values: 5 }, 
    { values: 2 }, 
    { values: 6 }, 
    { values: 6 },
    { values: 5 }
];

and i have tried this code

我已经试过这个代码

 function findMedian(m) {
        var middle = m.length - 1 / 2;
        if (m.length - 1 % 2 == 1) {
            return m[middle];
        } else {
            return (m[middle - 1] + m[middle]) / 2.0;
        }

    }

But it's return NaNvalue

但它是返回NaN

My calculation formula is

我的计算公式是

Find the median of the data. Place the number of data in ascending order. Then, mark the place whose value we take into account when calculating the median.

找出数据的中位数。将数据数量按升序排列。然后,标记我们在计算中位数时考虑其值的地方。

回答by Alnitak

This will do what you need - at the moment you've no logic to cope with reading the .valuesfield out of each element of the array:

这将满足您的需求 - 目前您没有逻辑来应对.values从数组的每个元素中读取字段:

function findMedian(data) {

    // extract the .values field and sort the resulting array
    var m = data.map(function(v) {
        return v.values;
    }).sort(function(a, b) {
        return a - b;
    });

    var middle = Math.floor((m.length - 1) / 2); // NB: operator precedence
    if (m.length % 2) {
        return m[middle];
    } else {
        return (m[middle] + m[middle + 1]) / 2.0;
    }
}

EDITI've padded out the code a bit compared to my original answer for readability, and included the (surprising to me) convention that the median of an even-length set be the average of the two elements either side of the middle.

编辑与我最初的可读性答案相比,我对代码进行了一些填充,并包含了(令我惊讶的)约定,即偶数长度集合的中值是中间任一侧两个元素的平均值。

回答by Mritunjay

Here about two things you have to be careful.

这里有两件事你必须小心。

1)Operator precedence

1)运算符优先级

When you are saying

当你说

var middle = m.length - 1 / 2;

It is same as

它与

 var middle = m.length - 0.5; //Because / has much precedence than -

So you should say

所以你应该说

 var middle = (m.length - 1) / 2;

Same problem with m.length - 1 % 2

同样的问题 m.length - 1 % 2

2)You are not rounding middleso it's looking for decimal indexes in array. Which I think will return undefined.

2)你没有四舍五入,middle所以它在数组中寻找十进制索引。我认为会回来的undefined

回答by Harry Stevens

For an array of numbers, e.g. [1,6,3,9,28,...]

对于数字数组,例如 [1,6,3,9,28,...]

// calculate the median
function median(arr){
  arr.sort(function(a, b){ return a - b; });
  var i = arr.length / 2;
  return i % 1 == 0 ? (arr[i - 1] + arr[i]) / 2 : arr[Math.floor(i)];
}

What the code is doing:

代码在做什么:

  1. Sort the numbers so that they are in order by value.
  2. Find out the median's index in the array. If the array's length is even, the median is the average of the two numbers on either side of the index.
  3. For arrays of odd length, it's easy to pluck out the middle number. But for arrays of even length, it's not. So, you test to find out whether your array is odd- or even-lengthed by finding out if dividing the array's length by two returns a whole number or not. If it's a whole number, that means the array's length is even, and you have to calculate the average of the two numbers on either side of the median.
  1. 对数字进行排序,使它们按值排列。
  2. 找出数组中中位数的索引。如果数组的长度是偶数,则中位数是索引两侧的两个数字的平均值。
  3. 对于奇数长度的数组,很容易取出中间的数字。但是对于偶数长度的数组,它不是。因此,您可以通过找出将数组的长度除以二是否返回整数来测试您的数组是奇数还是偶数。如果是整数,则意味着数组的长度是偶数,您必须计算中位数两侧的两个数字的平均值。

In your question, your array can be flattened like so:

在您的问题中,您的数组可以像这样展平:

var myArray = data.map(function(d){ return d.values; });

And to get the median, use the function above like so:

要获得中位数,请使用上面的函数,如下所示:

var myMedian = median(myArray); // 4.5

回答by disfated

In case you were wondering how to find median without using conditionals, here you are :)

如果您想知道如何在不使用条件的情况下找到中位数,那么您在这里:)

Mind ES6.

头脑 ES6。

/**
 * Calculate median of array of numbers
 * @param {Array<Number>} arr
 * @return {Number}
 */
function median(arr) {
    arr = [...arr].sort((a, b) => a - b);
    return (arr[arr.length - 1 >> 1] + arr[arr.length >> 1]) / 2;
}

To answer the question:

要回答这个问题:

median(data.map(x => x.values));

回答by cssimsek

Here's a snippet that allows you to generate an array of numbers with either even or odd length. The snippet then sorts the array and calculates the median, finally printing the sorted array and the median.

这是一个片段,允许您生成偶数或奇数长度的数字数组。该代码段然后对数组进行排序并计算中位数,最后打印排序后的数组和中位数。

(function() {
  function makeNumArray(isEven) {
    var randomNumArr = [];
    var limit = isEven ? 8 : 9;
    for (var i = 0; i < limit; i++) {
      randomNumArr.push(Math.ceil(Math.random() * 10));
    }
    return randomNumArr;
  }

  function getMedian(arrOfNums) {
    var result = [];
    var sortedArr = arrOfNums.sort(function(num1, num2) {
      return num1 - num2;
    });
    result.push("sortedArr is: [" + sortedArr.toString() + "]");
    var medianIndex = Math.floor(sortedArr.length / 2);
    if (arrOfNums.length % 2 === 0) {
      result.push((sortedArr[medianIndex-1] + sortedArr[medianIndex]) / 2);
      return result;
    } else {
      result.push(sortedArr[medianIndex]);
      return result;
    }
  }

  function printMedian(resultArr) {
    var presentDiv = document.querySelector('#presentResult');
    var stringInsert = '<div id="sortedArrDiv">' + resultArr[0].toString() + '<br>' + 'the median is: ' + resultArr[1].toString() + '</div>';
    if (!document.querySelector('#sortedArrDiv')) {
      presentDiv.insertAdjacentHTML('afterbegin', stringInsert);
    } else {
      document.querySelector('#sortedArrDiv').innerHTML = resultArr[0].toString() + "<br>" + 'the median is: ' + resultArr[1].toString();
    }
  };

  function printEven() {
    printMedian(getMedian(makeNumArray(1)));
  }

  function printOdd() {
    printMedian(getMedian(makeNumArray(0)));
  }


  (document.querySelector("#doEven")).addEventListener('click', printEven, false);

  (document.querySelector("#doOdd")).addEventListener('click', printOdd, false);


})();
#presentResult {
  width: 70%;
  margin: 2% 0;
  padding: 2%;
  border: solid black;
}
<h4>Calculate the median of an array of numbers with even (static length of 8) or odd (static length of 9) length. </h4>
<input type="button" value="Even length array of random nums" id="doEven">
<input type="button" value="Odd length array of random nums" id="doOdd">
<div id="presentResult"></div>

回答by Brijesh

Findmedian(arr) {

arr = arr.sort(function(a, b){ return a - b; });

 var i = arr.length / 2;


var result =  i % 1 == 0 ? parseInt((arr[i - 1] + arr[i]) / 2) + ',' + 
parseInt(arr[i]) : arr[Math.floor(i)];

return result;

}

it returns for odd number of array elements.

它返回奇数个数组元素。