You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

数组处理需求:移除keyValues中<20元素对应keyTimes同索引元素

Solution for Filtering keyTimes Based on keyValues Elements < 20

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 filter method loops through each element in keyTimes.
  • For every element, we use the current index to look up the matching value in keyValues.
  • We only retain the keyTimes element if its paired keyValues entry 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 corresponding keyValues element meets our condition. If yes, we add the time to the accumulator.
  • The final accumulator holds our filtered keyTimes array.

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 matching keyTimes[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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 03:29:08