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

124
Vistas
How can i modify indexing in a single object in javascript

I have an object list to store indexes just like that:

const initialIndexes = {
  0: [0,1,2],
  1: [0,1]
}

At this point I have a highlightedResultIndex variable. It gives an index like this:

highlightedResultIndex = 0 - case 1
highlightedResultIndex = 4 - case 2
highlightedResultIndex = 2 - case 3
...

And I finally try to get the following results by highlightedResultIndex

For the case 1:

result = {
 0: 0, // index from initialIndexes
 1: -1
}

For the case 2:

result = {
  0: -1,
  1: 1  // index from initialIndexes
}

For the case 3:

result = {
 0: 2  // index from initialIndexes
 1: -1
}

Maybe there is an easy method or there may be a certain algorithm for this, but I didn't know how to research it so I wanted to write it here. I would be glad if you help.

EDIT:

Let me put here some of examples

// This is data from the server side.
const initialIndexes = {
  0: [0,1,2,3],
  1: [0,1,2],
  2: [0,1,2],
  3: [0,1,2,3,4]
}

// So, I need to index object like this by highlightedResultIndex variable

// highlightedResultIndex = 0
{
 0:0,
1:-1,
2:-1,
3:-1
}

//  highlightedResultIndex = 6
{
0: -1,
1:2,
2:-1,
3:-1
}

//  highlightedResultIndex = 10
{
0: -1,
1:-1,
2:-1,
3:0
}
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You could take the wanted index value and reduce it by the lenght of the arrays until it fits into an array.

const
    initialIndexes = { 0: [0, 1, 2, 3], 1: [0, 1, 2], 2: [0, 1, 2], 3: [0, 1, 2, 3, 4] },
    getIndices = n => Object.fromEntries(Object
        .entries(initialIndexes)
        .map(([key, array]) => {
            const value = n >= 0 && n < array.length
                ? array[n]                           // or just n
                : -1;

            n -= array.length;
            return [key, value]; 
        })
    );

console.log(getIndices(0));  // { 0:  0, 1: -1, 2: -1, 3: -1 }
console.log(getIndices(6));  // { 0: -1, 1:  2, 2: -1, 3: -1 }
console.log(getIndices(10)); // { 0: -1, 1: -1, 2: -1, 3:  0 }
.as-console-wrapper { max-height: 100% !important; top: 0; }

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