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

174
Vistas
Im trying to use .filter, .sort, and .reduce on an array of numbers to return a string separated by a comma and a space

I am supposed to write a function that takes an array of numbers and returns a string. The function is supposed to use filter, sort AND reduce to return a string containing only odd numbers, separated by commas in ascending order.

I can't seem to get my .reduce method to actually return anything and my if conditions don't seem to work correctly... (for example, it adds a comma and space after the output of the last number like this "3, 17, ")

Here is the code I have made so far...

const numSelectString = (numArr) => {
    // use .filter to select only the odd numbers
  numArr.filter((num) => num % 2 !== 0)
  // use. sort to sort the numbers in ascending order
  .sort((a,b) => a-b)
  // use reduce to create the string and put the commas and spaces in
  .reduce((acc, next, index) => {
    
    if (index+1!==undefined) {
      return acc = acc + next + ', ';;
    } else {
      return acc + next;
    }
  },'')
}

const nums = [17, 34, 3, 12]
console.log(numSelectString(nums)) // should log "3, 17"

Does anyone have time to help me sort out my reduce method? I tried to pass in the index to determine if reduce is iterating on the last element to not output the ", " after the last element... but haven't got it to work... Also, I still don't understand why I keep getting "undefined" as my output!

Thanks for any help!

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

You could replace the check with just taking the addition and without a start value.

const
    numSelectString = numArr => numArr
        .filter((num) => num % 2 !== 0)
        .sort((a, b) => a - b)
        .reduce(
            (acc, next, index) => index
                ? acc + ', ' + next
                : next,
            ''
        );

console.log(numSelectString([17, 34, 3, 12]));
console.log(numSelectString([2, 4, 6]));
console.log(numSelectString([1, 2]));

about 4 years ago · Juan Pablo Isaza Denunciar

0

Instead of using index+1!==undefined, try this

const numSelectString = (numArr) => {

  const numArrLength = numArr.length;
  const arr = [...numArr];

  arr
    .filter((num) => num % 2 !== 0)
    .sort((a,b) => a - b)
    .reduce((acc, next, index) => {
       if (index < numArrLength - 1) return acc += `${next}, `;
       else return acc + `${next}`;
    }, "")

return arr;
}

It is also considered a good practice to not mutate the parameters.

Another method

Using the .join() method makes it way easy.

const numSelectString = (numArr) => {

const arr = [...numArr]
  arr
    .filter((num) => num % 2 !== 0)
    .sort((a,b) => a-b)
    .join(", ");

return arr;
}
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