Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

122
Visualizações
Insert item in specific index inside the array that is being looped

What is the best way to update an array by inserting the new element in specific index when certain condition is met while looping.

const exampleArray = [
  {item: 1, count: 5},
  {item: 2, count: 20},
  {item: 3, count: 10},
  {item: 6, count: 9}
  {item: 4, count: 5}]

I want to loop the exampleArray while keep track of count and insert new element right after when the count is greater than or equal to 10 and then reset the count to 0 for next loop

so the result I want is

const resultArray = [
  {item: 1, count: 5},
  {item: 2, count: 20},
  {item: 'new item 1 as count is over 10', count: 0},
  {item: 3, count: 10},
  {item: 'new item 2 as count is equal to 10', count: 0}, 
  {item: 6, count: 9},
  {item: 4, count: 5}, 
  {item: 'new item 3 as count is > 10, previous two counts (9 + 5 )', count: 0 }]

I tried this

let count = 0
exampleArray.forEach((item, index) => {
 count += item.count

 if(count >= 10) {
  exampleArray.splice(index + 1, 0, {item: 'item to be added', count: 0}
  count = 0
 }
})

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Both of these create a new array - if you want to overwrite, use let and asssign back to the original

TJ Suggested map and flat - that is a flatMap

const exampleArray = [
  {item: 1, count: 5},
  {item: 2, count: 20},
  {item: 3, count: 10},
  {item: 4, count: 5}];
  
let count = 0;  
const resultArray = exampleArray.flatMap(item => {
  count += item.count; 
  if (count >= 10) {
    count = 0
    return [item, {item:"new", count:0}]
  }  
  return item;
});

console.log(resultArray);

Reduce

const exampleArray = [
  {item: 1, count: 5},
  {item: 2, count: 20},
  {item: 3, count: 10},
  {item: 4, count: 5}];
  
let count = 0;
const resultArray = exampleArray.reduce((acc,cur) => {
  count += cur.count; 
  acc.push(cur);
  if (count >= 10) {
    count = 0
    acc.push({item:"new", count:0})
  }  
  return acc;
},[]);

console.log(resultArray);

about 4 years ago · Juan Pablo Isaza Relatório

0

I'd go for a simple for or for...of loop. If you're happy to create a new array (if not — I see you aren't in your question — see below):

const result = [];
for (const item of exampleArray) {
    count += item.count;
    result.push(item);
    if (count >= 10) {
        result.push({item: 'item to be added', count: 0});
    }
}

or (originally I used map...flat(), because I forgot again about flatMap; mplungjan reminded me):

let count = 0;
const result = exampleArray.flatMap(item => {
    count += item.count;
    if (count >= 10) {
        return [item, {item: 'item to be added', count: 0}];
    }
    return item;
});

Live Example:

const exampleArray = [
    {item: 1, count: 5},
    {item: 2, count: 20},
    {item: 3, count: 10},
    {item: 4, count: 5}
];
let count = 0;
const result = [];
for (const item of exampleArray) {
    count += item.count;
    result.push(item);
    if (count >= 10) {
        result.push({item: 'item to be added', count: 0});
    }
}
console.log(result);
count = 0;
const result2 = exampleArray.map(item => {
    count += item.count;
    if (count >= 10) {
        return [item, {item: 'item to be added', count: 0}];
    }
    return item;
}).flat();
console.log(result2);

If you really want to modify the existing array instead, the for loop lets you control the index variable:

for (let index = 0; index < exampleArray.length; ++index) {
    const item = exampleArray[index];
    count += item.count;
    if (count >= 10) {
        exampleArray.splice(index + 1, 0, {item: 'item to be added', count: 0});
        count = 0;
        ++index; // Skip the item we just added
    }
}

Live Example:

const exampleArray = [
    {item: 1, count: 5},
    {item: 2, count: 20},
    {item: 3, count: 10},
    {item: 4, count: 5}
];
let count = 0;
for (let index = 0; index < exampleArray.length; ++index) {
    const item = exampleArray[index];
    count += item.count;
    if (count >= 10) {
        exampleArray.splice(index + 1, 0, {item: 'item to be added', count: 0});
        count = 0;
        ++index; // Skip the item we just added
    }
}
console.log(exampleArray);

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda