如何从此数组中找到user_value最接近的值? 这是user_value变量,根据这个我需要从数组中找出最接近的值。
var user_value = 5500;
var array = [
{_id: 5809e269d60f577ae35f6add,
coins: 1000,
is_active: 1,
iconId: 4 },
{_id: 5809e269d60f577ae35f6ade,
coins: 2000,
is_active: 1,
iconId: 5 },
{_id: 5809e269d60f577ae35f6adf,
coins: 5000,
is_active: 1,
iconId: 6 },
{_id: 5809e269d60f577ae35f6ae0,
coins: 7000,
is_active: 1,
iconId: 7 },
{_id: 5809e269d60f577ae35f6ae1,
coins: 10000,
is_active: 1,
iconId: 8 },
{_id: 5809e269d60f577ae35f6ae2,
coins: 15000,
is_active: 1,
iconId: 9 } ];
答案 0 :(得分:2)
假设您将最接近的定义为Math.abs(array[i].coins - value);
,您只需要像下面那样迭代数组:
var user_value = 5500;
var array = [
{
coins: 1000,
is_active: 1,
iconId: 4
},
{
coins: 2000,
is_active: 1,
iconId: 5
},
{
coins: 5000,
is_active: 1,
iconId: 6
},
{
coins: 7000,
is_active: 1,
iconId: 7
},
{
coins: 10000,
is_active: 1,
iconId: 8
},
{
coins: 15000,
is_active: 1,
iconId: 9
}
];
function findClosest (value) {
// By default that will be a big number
var closestValue = Infinity;
// We will store the index of the element
var closestIndex = -1;
for (var i = 0; i < array.length; ++i) {
var diff = Math.abs(array[i].coins - value);
if (diff < closestValue) {
closestValue = diff;
closestIndex = i;
}
}
return closestIndex;
}
console.log("The closest index: " + findClosest(user_value));
答案 1 :(得分:1)
您可以使用绝对差异进行检查来使用迭代方法。
var value = 5500,
array = [{ _id: '5809e269d60f577ae35f6add', coins: 1000, is_active: 1, iconId: 4 }, { _id: '5809e269d60f577ae35f6ade', coins: 2000, is_active: 1, iconId: 5 }, { _id: '5809e269d60f577ae35f6adf', coins: 5000, is_active: 1, iconId: 6 }, { _id: '5809e269d60f577ae35f6ae0', coins: 7000, is_active: 1, iconId: 7 }, { _id: '5809e269d60f577ae35f6ae1', coins: 10000, is_active: 1, iconId: 8 }, { _id: '5809e269d60f577ae35f6ae2', coins: 15000, is_active: 1, iconId: 9 }],
result = array.reduce(function (r, a, i, aa) {
return i && Math.abs(aa[r].coins - value) < Math.abs(a.coins - value) ? r : i;
}, -1);
console.log(result);
&#13;
答案 2 :(得分:0)
var _ = require('underscore');
var user_value = 5500;
var array = [
{ _id: '5809e269d60f577ae35f6add',
coins: 1000,
is_active: 1,
iconId: 4 },
{ _id: '5809e269d60f577ae35f6ade',
coins: 2000,
is_active: 1,
iconId: 5 },
{ _id: '5809e269d60f577ae35f6adf',
coins: 5000,
is_active: 1,
iconId: 6 },
{ _id: '5809e269d60f577ae35f6ae0',
coins: 7000,
is_active: 1,
iconId: 7 },
{ _id: '5809e269d60f577ae35f6ae1',
coins: 10000,
is_active: 1,
iconId: 8 },
{ _id: '5809e269d60f577ae35f6ae2',
coins: 15000,
is_active: 1,
iconId: 9 } ];
function getClosest(array, target) {
var tuples = _.map(array, function(json) {
return [json, Math.abs(json.coins - target)];
});
//console.log(tuples);
return _.reduce(tuples, function(memo, val) {
return (memo[1] < val[1]) ? memo : val;
}, [-1, 999])[0];
}
console.log(getClosest(array, user_value))