Tengo una matriz como esta:
const array = ["something", "6", "somethingelse", "130", "carrot", "89", "monkey", "57", "plane", "71"];Necesito poder identificar cualquier índice con un "valor numérico" inferior a 65, y eliminar ese índice y el que está inmediatamente a la izquierda.
Entonces, en este caso, los números en la matriz que son menores que 65 son "6" y "57".
Necesito eliminar "6" y "algo", así como "57" y "mono".
y la matriz resultante sería:
const array = ["somethingelse", "130", "carrot", "89", "plane", "71"];Tengo el siguiente código hasta ahora:
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); }Para el código anterior, necesito especificar el valor del número exactamente, lo que elimina ese índice y el que está a la izquierda... El problema es que necesito especificar un rango, y no un valor exacto.
Por aquí ?
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) )Puede lograr fácilmente el resultado usando simple for loop
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);Puede iterar todos los índices y verificar el valor y eliminar, si es necesario.
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); Si no necesita la misma referencia de objeto de la array , puede filtrar la matriz.
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]));