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

126
Visualizações
Information about to Array in JAvascript

I would like to get find elements having same characters but in different order in an array. I made javascript below,is there any way to create Javascript function more basic? Can you give me an idea? Thank you in advance..

<p id="demo"></p>

<script>
const arr1 = ["tap", "pat", "apt", "cih", "hac", "ach"];
var sameChars = 0;
var subArr1 = [];

for(var i = 0; i < arr1.length; i++){
    for(var j = i+1; j < arr1.length; j++){
      if(!subArr1.includes(arr1[i]) && !subArr1.includes(sortAlphabets(arr1[i]))){
             subArr1.push(arr1[i]);
             sameChars++;
      }
   
      if(sortAlphabets(arr1[i]) == sortAlphabets(arr1[j])){
          if(!subArr1.includes(arr1[j])){
             subArr1.push(arr1[j]);
          }
      }
    }
}
function sortAlphabets(text1) {
    return text1.split('').sort().join('');
};

document.getElementById("demo").innerHTML = sameChars;

</script>

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

0

I would just use reduce. Loop over split the string, sort it, join it back. Use it as a key in an object with an array and push the items onto it.

const arr1 = ["tap", "pat", "apt", "cih", "hac", "ach"];

const results = arr1.reduce((obj, str) => {
  const key = str.split('').sort().join('');
  obj[key] = obj[key] || [];
  obj[key].push(str);
  return obj;
}, {});

console.log(Object.values(results));

about 4 years ago · Juan Pablo Isaza Relatório

0

You can get the max frequency value by building a map and getting the max value of the values.

const frequencyMap = (data, keyFn) =>
  data.reduce(
    (acc, val) =>
      (key => acc.set(key, (acc.get(key) ?? 0) + 1))
      (keyFn(val)),
    new Map());

const groupMap = (data, keyFn) =>
  data.reduce(
    (acc, val) =>
      (key => acc.set(key, [...(acc.get(key) ?? []), val]))
      (keyFn(val)),
    new Map());

const
  data   = ["tap", "pat", "apt", "cih", "hac", "ach"],
  sorted = (text) => text.split('').sort().join(''),
  freq   = frequencyMap(data, sorted),
  max    = Math.max(...freq.values()),
  groups = groupMap(data, sorted);

document.getElementById('demo').textContent = max;

console.log(Object.fromEntries(freq.entries()));
console.log(Object.fromEntries(groups.entries()));
.as-console-wrapper { top: 2em; max-height: 100% !important; }
<div id="demo"></div>

about 4 years ago · Juan Pablo Isaza Relatório

0

Maybe split the code into two functions - one to do the sorting and return a new array, and another to take that array and return an object with totals.

const arr = ['tap', 'pat', 'apt', 'cih', 'hac', 'ach'];

// `sorter` takes an array of strings
// splits each string into an array, sorts it
// and then returns the joined string
function sorter(arr) {
  return arr.map(str => {
    return [...str].sort().join('');
  });
}

// `checker` declares an object and
// loops over the array that `sorter` returned
// creating keys from the strings if they don't already
// exist on the object, and then incrementing their value
function checker(arr) {

  const obj = {};

  for (const str of arr) {

    // All this line says is if the key
    // already exists, keep it, and add 1 to the value
    // otherwise initialise it with 0, and then add 1
    obj[str] = (obj[str] || 0) + 1;
  }

  return obj;

}

// Call `checker` with the array from `sorter`
console.log(checker(sorter(arr)));
<p id="demo"></p>

Additional documentation

  • map

  • Loops and iteration

  • Spread syntax

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