Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

198
Vistas
How to add a new entry to an array after a certain property changes?

I am trying to add a new entry to an array after a certain property, in my case " place", changes. However, I have big problems to find a suitable approach, because the operation depends on the next object in the array.

const initalData = [
  { storyID: 1, place: 12, type: "Story" },
  { storyID: 5, place: 12, type: "Story" },
  { storyID: 99, place: 45, type: "Story" }, 
  { storyID: 8, place: 31, type: "Story" },
  { storyID: 16, place: 31, type: "Story" },
  { storyID: 20, place: 45, type: "Story" },
  { storyID: 22, place: 45, type: "Story" },
];
const targetData = [
  { placeID: 12, type: "Place" }, // new added entry based on the next  "place"
  { storyID: 1, place: 12, type: "Story" },
  { storyID: 5, place: 12, type: "Story" },
  { placeID: 45, type: "Place" }, // // new added entry based on the next  "place"
  { storyID: 99, place: 45, type: "Story" },
  { placeID: 31, type: "Place" }, // new added entry based on the next  "place"
  { storyID: 8, place: 31, type: "Story" },
  { storyID: 16, place: 31, type: "Story" },
  { placeID: 45, type: "Place" },// new added entry based on the next  "place"
  { storyID: 20, place: 45, type: "Story" },
  { storyID: 22, place: 45, type: "Story" },
];

Currently I have looked at groupBy("place") as a possible approach, but the ultimate array structure here is not what I need.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Here is the implementation

const initalData = [
    { storyID: 1, place: 12, type: "Story" },
    { storyID: 5, place: 12, type: "Story" },
    { storyID: 99, place: 45, type: "Story" },
    { storyID: 8, place: 31, type: "Story" },
    { storyID: 16, place: 31, type: "Story" },
    { storyID: 20, place: 45, type: "Story" },
    { storyID: 22, place: 45, type: "Story" },
];

let oldPlace = null;
let resultData = [];

for (let row of initalData) {
    if (row.place != oldPlace) {
        resultData.push({ placeID: row.place, type: "Place" });
        oldPlace = row.place;
    }
    resultData.push(row);
}

console.log (resultData);

enter image description here

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda