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

172
Vistas
Finding two occurances of value in array with nothing in-between, or adjacent

I have an array where I want to check for all instances of a specific letter where there are empty values in-between, or they are adjacent.

let myArray1 = ['A',,,,,'A'] //function returns [0,5]
let myArray2 = ['A',,,'E',,'A'] //function returns []
let myArray3 = [,,'A',,'A','G'] //function returns [2,4]
let myArray4 = [,,'A','A','G'] //function returns [2,3]
let myArray5 = [,,'A','A','G','A'] //function returns [2,3]

I've been trying with a for loop and push to array but I'm getting muddled.

Any ideas on how to do this function?

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

0

You could use .findIndex() to find the first non empty value (ie: character) and its index in your array. You can then use .findIndex() again on your array to find the second non-empty value that appears after your first character. If the first character and the second character match then you can return the indexes, otherwise you can return an empty array:

const getRange = (arr) => {
  const first = arr.findIndex(c => c !== undefined);
  const second = arr.findIndex((c, i) => i !== first && c !== undefined);
  
 return first !== -1 && arr[first] === arr[second] ? [first, second] : [];
}

console.log(getRange([,,,,,]));
console.log(getRange(['A',,,,,'A']));
console.log(getRange(['A',,,'E',,'A']));
console.log(getRange([,,'A',,'A','G']));
console.log(getRange([,,'A','A','G']));
console.log(getRange([,,'A','A','G','A']));

To optimize, you can do this with one-pass using a regular for..of loop by iterating the .entries() of the array;

const getRange = (arr) => {
  let first = -1;
  let second = -1;
  for(const [i, char] of arr.entries()) {
    if(char !== undefined && first === -1)
      first = i;
    else if(char !== undefined && second === -1)
      second = i;
  }
  return first !== -1 && arr[first] === arr[second] ? [first, second] : [];
}

console.log(getRange([,,,,,]));
console.log(getRange(['A',,,,,'A']));
console.log(getRange(['A',,,'E',,'A']));
console.log(getRange([,,'A',,'A','G']));
console.log(getRange([,,'A','A','G']));
console.log(getRange([,,'A','A','G','A']));

about 4 years ago · Juan Pablo Isaza Denunciar

0

function getMyResult(itemToSearch, array) {
    var firstIndex;
    var secondIndex;
    for (var i = 0; i < array.length; i++) {
        if (array[i] == itemToSearch) {
            if (firstIndex == null)
                firstIndex = i;
            else {
                secondIndex = i;
                break; // break loop as we got two success indices
            }
        } else if (array[i] != null) {
            if (firstIndex != null) {
                // something got in between the items
                break;
            }
        }
    }
    if (firstIndex != null && secondIndex != null)
        return [firstIndex, secondIndex]; // success indices
    return []; //not success
}

let myArray1 = ['A',,,,,'A'];
let myArray2 = ['A',,,'E',,'A']; //function returns []
let myArray3 = [,,'A',,'A','G']; //function returns [2,4]
let myArray4 = [,,'A','A','G']; //function returns [2,3]
let myArray5 = [,,'A','A','G','A']; //function returns [2,3]

console.log(
  getMyResult('A', myArray1)
);
console.log(
  getMyResult('A', myArray2)
);
console.log(
  getMyResult('A', myArray3)
);
console.log(
  getMyResult('A', myArray4)
);
console.log(
  getMyResult('A', myArray5)
);

The above function getMyResult will solve your problem.

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can use for loop to keep track of last value and its index, if last value is same as current value you can break the loop otherwise you can reset last value and start index.

const getRange = (arr) => {
  let last = '', start = -1, end = -1;
  for(let i = 0; i < arr.length; i++) {
    if(arr[i]) {
      if(last === arr[i]) {
        end = i;
        break;
      } else {
        start = i;
        last = arr[i];
      }
    }
  }
  return end !== -1 ? [start, end]: []
}

console.log(getRange(['A',,,,,'A']));
console.log(getRange(['A',,,'E',,'A']));
console.log(getRange([,,'A',,'A','G']));
console.log(getRange([,,'A','A','G']));
console.log(getRange([,,'A','A','G','A']));
console.log(getRange([,,,'E',,'E',,,,,'E']));
console.log(getRange([,,'A',,'G','A',,,,,'A']));
console.log(getRange(['A',,,'E',,'A']));

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