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

175
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 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