如何编写方法判断数字所属区间并返回对应对象Key(可使用Lodash)
Hey Johnny! Great question—let's break down how to build this function using Lodash, which will make sorting and traversal super straightforward.
Solution Using Lodash
First, let's lock in the core logic we need:
- If the input number falls between
section1's value (100) andsection2's value (200) → returnsection1 - If it's between 200 and 300 → return
section2 - If it's 300 or higher → return
section3
(We'll also handle edge cases like numbers lower than 100, just in case you need it)
Here's a clean, readable implementation:
// Import Lodash first (make sure it's installed in your project) // const _ = require('lodash'); // For Node.js // import _ from 'lodash'; // For ES Modules const getMatchingSection = (inputNum) => { // Your target section mapping const sectionMap = { 'section1': 100, 'section2': 200, 'section3': 300 }; // Step 1: Convert the object to [key, value] pairs, then sort by value const sortedSections = _.sortBy(_.entries(sectionMap), ([_, value]) => value); // Step 2: Find the first section with a value greater than the input number const firstHigherSection = _.find(sortedSections, ([_, value]) => value > inputNum); if (firstHigherSection) { const sectionIndex = sortedSections.indexOf(firstHigherSection); // If input is smaller than all values, return the first section // Otherwise, return the section right before the first higher value return sectionIndex > 0 ? sortedSections[sectionIndex - 1][0] : firstHigherSection[0]; } // If input is >= the largest section value, return the last section return sortedSections[sortedSections.length - 1][0]; }; // Test the function with your examples! console.log(getMatchingSection(120)); // Output: 'section1' console.log(getMatchingSection(267)); // Output: 'section2' console.log(getMatchingSection(350)); // Output: 'section3' console.log(getMatchingSection(80)); // Output: 'section1' (adjust behavior if needed)
How This Works:
_.entries(sectionMap): Turns your object into an array of[key, value]pairs (e.g.,[['section1', 100], ['section2', 200]]), which makes sorting and iterating way easier._.sortBy(...): Ensures we process sections from smallest to largest value, so we can check intervals in logical order._.find(...): Quickly locates the first section where the value is larger than our input. The section immediately before this one is the interval our number falls into.- Edge Case Handling: We cover numbers smaller than all section values and numbers larger than the largest value, so the function never breaks unexpectedly.
Quick Adjustment for Exact Matches
If you want numbers that exactly match a section value (like 200) to return that section instead of the previous one, just tweak the _.find condition from value > inputNum to value >= inputNum. That way, 200 would return section2 instead of section1.
内容的提问来源于stack exchange,提问作者Johnny Kay
相关产品推荐
相关产品推荐

