在javascript中找到数组的中值(8个值或9个值)

时间:2021-08-10 21:17:52

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 NaN value

但它返回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.

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

5 个解决方案

#1


11  

This will do what you need - at the moment you've no logic to cope with reading the .values field 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;
    }
}

EDIT I'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.

编辑我已经将代码与我原来的可读性答案进行了一些比较,并且包含了(令我惊讶的)惯例,即偶数长度集的中位数是中间两侧的两个元素的平均值。

#2


5  

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 middle so it's looking for decimal indexes in array. Which I think will return undefined.

2)你没有舍入中间,所以它在数组中寻找小数索引。我认为这将返回undefined。

#3


4  

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

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

// calculate the median
function median(arr){
  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. 对数字进行排序,使它们按值排序。
  3. 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.
  4. 找出数组中的中位数索引。如果数组的长度是偶数,则中位数是索引两侧的两个数字的平均值。
  5. 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.
  6. 对于奇数长度的数组,可以很容易地取出中间数字。但对于长度均匀的阵列,它不是。因此,您通过查找将数组的长度除以2是否返回整数来测试以确定您的数组是奇数还是偶数。如果它是一个整数,则意味着数组的长度是偶数,并且您必须计算中位数两侧的两个数字的平均值。

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

#4


0  

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>

#5


0  

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.

它返回奇数个数组元素。

#1


11  

This will do what you need - at the moment you've no logic to cope with reading the .values field 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;
    }
}

EDIT I'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.

编辑我已经将代码与我原来的可读性答案进行了一些比较,并且包含了(令我惊讶的)惯例,即偶数长度集的中位数是中间两侧的两个元素的平均值。

#2


5  

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 middle so it's looking for decimal indexes in array. Which I think will return undefined.

2)你没有舍入中间,所以它在数组中寻找小数索引。我认为这将返回undefined。

#3


4  

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

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

// calculate the median
function median(arr){
  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. 对数字进行排序,使它们按值排序。
  3. 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.
  4. 找出数组中的中位数索引。如果数组的长度是偶数,则中位数是索引两侧的两个数字的平均值。
  5. 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.
  6. 对于奇数长度的数组,可以很容易地取出中间数字。但对于长度均匀的阵列,它不是。因此,您通过查找将数组的长度除以2是否返回整数来测试以确定您的数组是奇数还是偶数。如果它是一个整数,则意味着数组的长度是偶数,并且您必须计算中位数两侧的两个数字的平均值。

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

#4


0  

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>

#5


0  

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.

它返回奇数个数组元素。