Lehmann
Lehmann

Reputation: 11

How can I avoid having repeating characters in a string javascript and more?

I was solving this with a function that has 2 parameters (s, r); s, is the string and r, the number that indicates how many times it can be repeated

Example: if I enter ("aassaa", 1) it has to give me as "asa"

but mi code not work with ("aadaa",1) because what comes out is ("ad") and not ("ada") i need ("ada") strong text The code I am trying to do:

function unique(s,r) {
  if (Array.isArray(s)) s = s.join(""); // Comprobar si es array y unirlo
  if ((typeof s === "string") === false) return; // Si el elemento no es un string, detener la ejecución de la función
  let repeated = []; // Definir elementos repetidos
  const split = s.split(""); // Dividir el string
  split.forEach(el => { // Recorrer cada letra
    if (split.filter(w => w === el).length > 1) { // Comprobar si hay más de un elemento en el array devuelto por filter
      repeated.push(split.filter(w => w === el)); // Añadir un nuevo elemento a repeated
    }
  });
  repeated = Array.from(new Set(repeated.map(JSON.stringify))).map(JSON.parse); // Obtener los arrays únicos
  // console.log(repeated);
  s = [...new Set(s.split(""))].join(""); // Obtener un string con solo letras únicas
  repeated.forEach(el => { // Recorrer repeated
    s = s.replace(el[0], ""); // Reemplazar el elemento actual para no tener letras de el array repetido
    while(el.length > r) {
      el.splice(0, true); // Eliminar el primer elemento
    }
  });
  s += repeated.flat().join("");
  return s;
}

console.log(unique("aaa", 1)); // a
console.log(unique("aaa", 2)); // aa
console.log(unique(["a","a","b","a","a","a"], 2)); // baa
console.log(unique(["a","a","b","a","a","a"], 1)); // ba

Upvotes: 1

Views: 219

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386550

You could filter an array of characters by using a count variable.

function unique(s, r) {
    if (Array.isArray(s)) s = s.join("");
    if (typeof s !== "string") return;
    let count = 0;

    return [...s]
        .filter((c, i) => {
            if (s[i - 1] === c) return count++ < r;
            count = 1;
            return true;
        })
        .join('');
}

console.log(unique("aaa", 1)); // a
console.log(unique("aaa", 2)); // aa
console.log(unique(["a", "a", "b", "a", "a", "a"], 2)); // aabaa
console.log(unique(["a", "a", "b", "a", "a", "a"], 1)); // aba

Upvotes: 1

Related Questions