数组处理需求:移除keyValues中<20元素对应keyTimes同索引元素
Got it, let's walk through how to solve this problem. The core idea is to keep elements in keyTimes only if their corresponding index in keyValues has a value greater than or equal to 20 (since we need to remove entries where keyValues is less than 20). Here are a few practical, easy-to-implement approaches:
Method 1: Using Array.filter() with Index
This is the most concise and readable approach for modern JavaScript. We can use the filter method's built-in index parameter to cross-check values between the two arrays:
const keyValues = [15, 25, 18, 30, 10]; const keyTimes = [100, 200, 300, 400, 500]; const filteredKeyTimes = keyTimes.filter((_, index) => keyValues[index] >= 20); console.log(filteredKeyTimes); // Output: [200, 400]
Explanation:
- The
filtermethod loops through each element inkeyTimes. - For every element, we use the current
indexto look up the matching value inkeyValues. - We only retain the
keyTimeselement if its pairedkeyValuesentry isn't less than 20.
Method 2: Using Array.reduce()
If you need more flexibility (like collecting extra data alongside the filtered times), reduce is a great alternative:
const keyValues = [15, 25, 18, 30, 10]; const keyTimes = [100, 200, 300, 400, 500]; const filteredKeyTimes = keyTimes.reduce((acc, time, index) => { if (keyValues[index] >= 20) { acc.push(time); } return acc; }, []); console.log(filteredKeyTimes); // Output: [200, 400]
Explanation:
- We start with an empty accumulator array (
[]). - For each entry in
keyTimes, we check if the correspondingkeyValueselement meets our condition. If yes, we add the time to the accumulator. - The final accumulator holds our filtered
keyTimesarray.
Method 3: Traditional for Loop
For maximum compatibility (e.g., working with older JavaScript environments), a classic loop is reliable and easy to follow:
const keyValues = [15, 25, 18, 30, 10]; const keyTimes = [100, 200, 300, 400, 500]; const filteredKeyTimes = []; for (let i = 0; i < keyValues.length; i++) { if (keyValues[i] >= 20) { filteredKeyTimes.push(keyTimes[i]); } } console.log(filteredKeyTimes); // Output: [200, 400]
Explanation:
- We loop through each index of
keyValues(assuming both arrays are the same length—critical for this problem to work correctly). - For each index, we check if
keyValues[i]is >=20. If it is, we add the matchingkeyTimes[i]to our result array.
Quick Note:
Double-check that keyValues and keyTimes have identical lengths before using any of these methods. Mismatched lengths could lead to index out-of-bounds errors.
内容的提问来源于stack exchange,提问作者Aleksandar

