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

242
Visualizações
Find the duplicate string in the array and add an incrementing number at the end

I'm working in javascript & trying to figure out an algorithm to append incremental numbers to strings, based on existing strings in the program.

Input:

['Untitled Form', 'Untitled Form - 1', 'Untitled Form - 5', 'Untitled Form - 3', 'Untitled Form - 4', "Untitled Form"];

So say the user wants to add another string to this list, and they've selected "Untitled Form" as the string to add. So given the input and the existing list, the algorithm would search in the list to check if there is any incrementing number missing e.g In the above code the "Untitled Form - 2" is missing, It should return "Untitled Form - 2" as the new string to add.

Output:

['Untitled Form', 'Untitled Form - 1', 'Untitled Form - 5', 'Untitled Form - 3', 'Untitled Form - 4', "Untitled Form - 2"];

It's the same function as in Windows Explorer where you keep adding New Folders ("New Folder (1)", "New Folder (2)" and on and on)

I have a solution for this problem but I think it is not very efficient and the algorithm also checks for the highest number and adds the incremental number after that is "Untitled Form - 6".

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

0

You can do it by extracting existing indexes and sort them, then compare every index with next one, if difference is bigger than 1, so you can realize that there is an missed index in that place.like this:

let list = ['Untitled Form', 'Untitled Form - 1', 'Untitled Form - 5', 'Untitled Form - 3', 'Untitled Form - 4'];

const findNextIndex = (arr)=> {
    const sortedArr = arr.map(item => Number(item.split('-')[1] || 0)).sort((a,b)=> a-b);
    if(!sortedArr.includes(0)) return 0;
    let index = sortedArr[sortedArr.length-1] + 1; //maximum value
    for(let i =0; i< sortedArr.length; i++){
      if(sortedArr[i+1] - sortedArr[i] > 1){
        index = sortedArr[i] + 1;
        break;
      }
    }
    return index;
}

const nextIndex = findNextIndex(list);
list = [...list, `Untitled Form${nextIndex ? ` - ${nextIndex}` : ''}`]
console.log(list)

about 4 years ago · Juan Pablo Isaza Relatório

0

This should work

  1. Sort array so it becomes
    [
        [0] => 'Untitled Form',
        [1] => 'Untitled Form - 1',
        [2] => 'Untitled Form - 2',
        ....
    ]
  1. loop through, and findIndex that indexInTitle doesn't match array's index.

  2. If found, return that index else incremental Index,

const listMissing2 = ['Untitled Form', 'Untitled Form - 1', 'Untitled Form - 5', 'Untitled Form - 3', 'Untitled Form - 4'];
const listNotMissing = ['Untitled Form', 'Untitled Form - 1', 'Untitled Form - 5', 'Untitled Form - 3', 'Untitled Form - 4', 'Untitled Form - 2'];

const findMissingOrIncrementIndex = list => {
  const sortedList = list.sort();
  const missingIndex = sortedList.findIndex((title, index) => {
    const [, indexInTitle] = title.split(' - ');
    return index > 0 && Number(indexInTitle) !== index;
  });
  return (missingIndex > -1) ? missingIndex : list.length;
}

console.log(findMissingOrIncrementIndex(listMissing2));
console.log(findMissingOrIncrementIndex(listNotMissing));

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