javascript比较数字和对象键并获取最小的值

时间:2018-11-06 16:27:00

标签: javascript arrays object ecmascript-6

说我们有

const list = {
  1: "a",
  10: "b",
  20: "c",
  30: "d",
  40: "e"
};

const value = 15;

如何有效地将值与对象键进行比较并获得对应的较小范围的值?并且在此示例中,预期答案为b,因为15在10到20之间。

我想这样:

for(var i=0; i < keys.length; i++){
    const item = parseInt(keys[i],10);
    if (item == keys[i]) {
      return keys[i];
    }
  }

但是效率不高...

5 个答案:

答案 0 :(得分:2)

您可以使用Object.keys将所有对象键保存在新数组中,并在.some(按@Keith的建议)中停止循环(return true),直到当前值变大,然后value,您的结果将存储在previous var

const list = {
  1: "a",
  10: "b",
  20: "c",
  30: "d",
  40: "e"
};

const value = 15;
let previous = 0;

Object.keys(list).some(k => {
  if (k > value) {
    return true;
  } 
  previous = k
});

console.log(list[previous]);

答案 1 :(得分:2)

您可以使用Array.findIndex()查找高于该值的第一个索引。如果未找到任何元素(返回值为-1),则将元素作为最后一个键,否则将其值为keys[index - 1。如果该值小于1st键,它将返回undefined

const findLowerClosest = (value, arr) => {
  const keys = Object.keys(list);
  const index = keys.findIndex(key => +key > value);
  const atKey = index !== -1 ? index - 1 : keys.length - 1;
  return arr[keys[atKey]];
}

const list = { 1: "a", 10: "b", 20: "c", 30: "d", 40: "e" };

console.log(findLowerClosest(15, list)); // b
console.log(findLowerClosest(75, list)); // e
console.log(findLowerClosest(-3, list)); // undefined

答案 2 :(得分:2)

如果像您的示例中那样对键进行了预排序,请使用二进制搜索log(n)时间复杂度。问题在于,将键转储到数组中是一次性线性步骤(如果需要,一次性排序将为O(n log n)),因此如果您打算运行多个搜索,则值得考虑在一个结构上。

const bisect = (a, target, lo=0, hi=a.length-1) => {
  while (lo <= hi) {
    const mid = ~~((hi - lo) / 2 + lo);

    if (a[mid] === target) {
      return a[mid];
    }
    else if (a[mid] < target) {
      lo = mid + 1;
    }
    else {
      hi = mid - 1;
    }
  }
  
  return a[~~((hi-lo)/2+lo)];
};

const list = {
  1: "a",
  10: "b",
  20: "c",
  30: "d",
  40: "e"
};

const keys = Object.keys(list);
console.log(list[bisect(keys, 15)]);
console.log(list[bisect(keys, 16)]);
console.log(list[bisect(keys, -50)]);
console.log(list[bisect(keys, 50)]);

答案 3 :(得分:1)

您可以使用 // no need to assign variables here, commented out and using originals below // $cat_name = $catname; // $cat_sur = $surnameCat; // $cat_city = $cityCat; // $cat_dob = $catDob; // $cat_bio = $catBio; // $cat_slug = sanitize_title_with_dashes($cat_name); $my_cat = array( 'cat_name' => $catname, 'category_description' => $catBio, // this is a _custom meta field_, so doesn't get inserted here... // 'cat_title' => $cat_sur, 'category_nicename' => sanitize_title_with_dashes($catname), 'category_parent' => 0 ); // get the category ID from the insert $cat_id = wp_insert_category( $my_cat ); if( ! is_wp_error( $cat_id ) && (int)$cat_id ) { // NOW, add the metadata... add_term_meta( $cat_id, '_pagetitle', $surnameCat ); echo json_encode("Category added successfully"); } else { echo json_encode("That category already exists"); } 来获取小于15的值,然后执行filter,然后将其用作从对象中检索值的键

Math.max

答案 4 :(得分:1)

您还可以sort键,然后使用reduce查找目标范围的下键:

const list = {
  1: "a",
  10: "b",
  20: "c",
  30: "d",
  40: "e"
};

const value = 15;
const answer = list[Object.keys(list)
                     .map(a => parseInt(a))
                     .sort((a, b) => a - b)
                     .reduce((acc, curr) => (acc < value && value < curr) ? acc : curr)];
                     
console.log(answer);

相关问题