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

127
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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