从数组中获取最接近的数字匹配项,必须更低
Get the closest number match from an array, must be lower
>我有一个数字数组,如下所示:
[10000 , 15000 , 20000 , 25000 , 30000]
我得到一个变量,它会有所不同,并且可以在数组范围内的任何地方,例如 23,500。
我需要从数组中找到最接近的数字,但它也必须小于给定的变量。
最简单的方法是什么?(可以使用jQuery)
编辑:
我试过这个:
salary = data[3]; // what im trying it on, this = 60001
// the array is built from a select
$.each($('#home-salary-from').children(), function(){
salaryArray.push($(this).attr('id'))
})
//returns [0, 10000 , 15000 , 20000 ...] etc up to 100000.
salaryFrom = salaryArray.filter( function(i){ return i <= salary }).pop();
console.log(salaryFrom)
//always returns 100000 ??
只是为了好玩:
var max = 23500,
arr = [10000 , 15000 , 20000 , 25000 , 30000],
closest;
// Solution 1
closest = arr.push( max ) && arr.sort()[ arr.indexOf( max ) - 1 ];
// Solution 2
closest = arr.filter( function(i){ return i <= max }).pop();
// Solution 3
closest = arr.sort(function(a,b){ return max >= b ? 1 : -1; })[0];
// Solution 4
closest = Math.max.apply(null,arr.filter(function(i){ return max - i >= 0 }));
演示
var x = [10000, 15000, 20000, 25000, 30000];
function find_closest(y) {
var z = [];
$.each(x, function (i, val) {
if (y > val) {
z.push(val);
}
});
z.sort();
return (z[z.length - 1]);
}
alert(find_closest(23500));
像这样的东西怎么样:
Array.prototype.closest = function(value) {
var res = 0;
for (var i=0; i<this.length; i++) {
if (this[i] > res && this[i] < value) res=this[i];
}
return res;
}
使用方式如下:
var numb = [10000 , 15000 , 20000 , 25000 , 30000].closest(23500);
小提琴
var arr = [10000, 15000, 20000, 25000, 30000];
var v = 23500;
var out = arr
.map(function(el) { return el - v; })
.filter(function(el) { if (el < 0) return el; });
var found = arr[out.indexOf(Math.max.apply(null, out))] || 'No match';
小提琴
我们可以通过这些简单的代码 snnipets 获得最接近的值 -
function getClosestValue(array,value)
{
var closestValue = null;
for(i=0; i<=array.length;i++)
{
if(array[i] > value &&
(closestValue == null || array[i] < closestValue))
{
closestValue = array[i];
}
}
return closestValue;
}
var numb = [10000 ,24000 ,20000 ,23700, 25000];
alert(getClosestValue(numb,23500));
相关文章:
- 从json子数组获取数据
- 从javascript数组获取php的日期时间
- 从表中的 JSON 数组获取数据
- 每个表的2D数组获取坐标JTSL,JAVASCRIPT
- javascript从元素到数组获取文本
- 如何从数组获取链接以在youtube Iframe API中播放
- JSON 编码多维数组获取值
- 如何从两个 JSON 数组获取增量
- 通过单击按钮数组获取隐藏 html 元素值的当前数组
- 在 JavaScript 中从内部数组获取数据
- 从数组获取非重复索引在 0 时失败
- JavaScript 从对象中的数组获取数组
- 如何通过 ajax 将 php 数组作为 javascript 数组获取
- 快速从 2D 数组获取索引,无需迭代 jquery
- 从 Nodejs socketio 数组获取所有套接字 id
- 无法动态从 json 数组获取数据
- 如何在javascript中使用数组获取和设置html标签的值
- jQuery对象数组获取一个项作为jQuery对象
- 如何在不向输出数组获取空值的情况下拆分字符串
- 从输入到数组获取数据