如何使用 "range" 在数组中查找数字,然后删除该索引以及紧靠其左侧的那个?

How do I use a "range" to find a number in an array, then remove that index, and the one immediately the left of it?

我有一个这样的数组:

const array = ["something", "6", "somethingelse", "130", "carrot", "89", "monkey", "57", "plane", "71"];

我需要能够识别“数字值”小于 65 的任何索引,并删除该索引和紧靠其左侧的索引。

所以在这种情况下,数组中小于 65 的数字是“6”和“57”。

我需要删除“6”和“something”,以及“57”和“monkey”。

结果数组将是:

const array = ["somethingelse", "130", "carrot", "89", "plane", "71"];

到目前为止我有以下代码:

const array = ["something", "6", "somethingelse", "130", "carrot", "89", "monkey", "57", "plane", "71"];
const range = 65 //I need to specify a range here, and not an exact number
const remove_array_index = array.findIndex(a =>a.includes(range));
if(array > -1){  //having -1 in .splice returns unintended results, so this tests if an index was found that matches the range
  array.splice(remove_array_index-1, 2);
}

对于上面的代码,我需要准确地指定数字值,这会删除该索引和它左边的那个.....问题是我需要指定一个范围,而不是一个确切的值。

您可以使用简单的 for 循环轻松获得结果

const array = [
  "something",
  "6",
  "somethingelse",
  "130",
  "carrot",
  "89",
  "monkey",
  "57",
  "plane",
  "71",
];

const result = [], range = [0, 65];
for (let i = 0; i < array.length; i += 2) {
  const str = array[i];
  const num = array[i + 1];

  if (range[0] < num && num > range[1]) result.push(str, num);
}
console.log(result);

您可以迭代所有索引并检查值并在必要时删除。

const
    remove = (array, [lower, upper]) => {
        let i = 0;
        
        while (i < array.length) {
            if (+array[i + 1] >= lower && +array[i + 1] <= upper) {
                array.splice(i, 2);
                continue;
            }        
            i += 2;
        }
        return array;
    },
    array = ["something", "6", "somethingelse", "130", "carrot", "89", "monkey", "57", "plane", "71"];

remove(array, [0, 65]);

console.log(array);

如果您不需要来自 array 的相同对象引用,您可以过滤数组。

const
    remove = (array, [lower, upper]) => array.filter((del => (_, i, { [ i + 1] : v }) => {
        if (del) return del = false;
        if (i % 2 === 0 && +v >= lower && +v <= upper) {
            del = true;
            return false;
        }
        return true;
    })()),

    array = ["something", "6", "somethingelse", "130", "carrot", "89", "monkey", "57", "plane", "71"];

console.log(remove(array, [0, 65]));

这边?

const array = 
  [ 'something',     '6'
  , 'somethingelse', '130'
  , 'carrot',        '89'
  , 'monkey',        '57'
  , 'plane',         '71'
  ] 
const range = 65

for (let index = array.length -1; index > 0; index -= 2)  
  {
  if (Number(array[index]) < range) array.splice(index-1, 2)
  }
  
console.log( JSON.stringify(array) )