const array = [{ id: "U", T: "001" }, { id: "R", T: "002" }, { id: "U", T: "003" }, { id: "R", T: "004" }, { id: "U", T: "005" }, ] La matriz anterior puede tener varios objetos con id: 'R' y quiero ignorar todos los objetos que están antes id: 'R' .
Esperado:
const array = [ { id: "U", T: "005"}]alguien me puede ayudar con esto por favor
Array#map , obtenga la lista de IDArray#lastIndexOf , obtenga el índice de la última aparición de la identificación "R"Array#splice , obtenga el subarreglo de destino siguiendo este índice const array = [ { id: "U", T: "001" }, { id: "R", T: "002" }, { id: "U", T: "003" }, { id: "R", T: "004" }, { id: "U", T: "005" } ]; const ids = array.map(({ id }) => id); const index = ids.lastIndexOf("R") + 1; const res = array.splice(index); console.log(res);De acuerdo con todas las respuestas anteriores, pero ¿por qué vamos con el mapa , el corte , la inversión y todo eso? Simplemente podemos usar solo un bucle en lugar de los que se muestran a continuación. Teniendo en cuenta el tiempo también, si la longitud de la matriz aumenta la combinación de cualquiera de los mapas, invertir, dividir, empalmar toma mucho tiempo
const array = [{ id: "U", T: "001" }, { id: "R", T: "002" }, { id: "U", T: "003" }, { id: "R", T: "004" }, { id: "U", T: "005" }, ]; let newArr = []; for(let i = array.length - 1; i >= 0; i--){ if(array[i].id === 'R') break; else newArr.push(array[i]) } console.log(newArr);Matriz inversa, encontrar el índice de la primera R, matriz de cortes...
const array = [{ id: "U", T: "001" }, { id: "R", T: "002" }, { id: "U", T: "003" }, { id: "R", T: "004" }, { id: "U", T: "005" } ] const cheak = (element) => element.id === "R" console.log(array.reverse().slice(0, array.findIndex(cheak)).reverse());