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

149
Visualizações
Javascript :higher order functions

I am new to coding and am practising higher order functions. Given the below question:

Write a function which will split an array into two arrays (i.e. partition it).

It will take two parameters, the first is an array of Integer values, and the second will be a callback which will return a boolean. If the callback returns true for an element, it should be placed into the left array, otherwise it should be placed into the right array.

Examples:

  • partition([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], n => n % 2 === 0) should look like this: [[2, 4, 6, 8, 10], [1, 3, 5, 7, 9]]
  • partition([-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5], n => n < 0) should look like this: [[-5, -4, -3, -2, -1], [0, 1, 2, 3, 4, 5]]
const partition = function(arr, callback) {
    // IMPLEMENT ME
};

I came up with the below:

const array = [];
arr.filter((integers) => {
  if (integers === callback) {
    array.push(integers);
    return integers;
  }
});
};

partition([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], (n) => n % 2 === 0);
partition([-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5], (n) => n < 0);

I am stuck and unable to understand how to use .filter with callback, how do I split it using the .filter way, can you please guide me with .filter method for the above question.

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

0

The filter function only allows you to return an array matching a condition. Therefore, if you want to build two array with the filter function, you can use it like that:

let partition = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let evenPartition = partition.filter(x => x % 2 === 0);
let oddPartition = partition.filter(x => x % 2 !== 0);
//Even partition : [2, 4, 6, 8, 10]
//Odd partition : [1, 3, 5, 7, 9]

You can also use the map function:

let partition = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let finalResult=[[], []];
partition.map(x => {
   if(x % 2 === 0)
      finalResult[0].push(x);
   else
      finalResult[1].push(x);
});

//Final result: [[2, 4, 6, 8, 10], [1, 3, 5, 7, 9]]
about 4 years ago · Juan Pablo Isaza Relatório

0

You need to filter the values which return true for the callback and collect all other values and return a new array with the values from filtering and the other collected values.

const partition = function(arr, callback) { // IMPLEMENT ME
    const array = [];
    return [
        arr.filter(value => {
            if (callback(value)) return true;
            array.push(value);
        }),
        array
    ];
};

console.log(partition([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], n => n % 2 === 0)); // [[2, 4, 6, 8, 10], [1, 3, 5, 7, 9]]

console.log(partition([-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5], n => n < 0)); // [[-5, -4, -3, -2, -1], [0, 1, 2, 3, 4, 5]]

about 4 years ago · Juan Pablo Isaza Relatório

0

Array.filter should take a callback that returns a boolean. If the callback returns true, it keeps the value in the resulting array, and if it returns false it does not add it to the array.

If you want to continue to use filter, what you have is close to working, except for the fact that you are checking for strict equality between each element and the callback function when you should instead be calling said function with callback(integer).

You also need to store the output of the filter into the second array if you want to use it.

const leftArray = [];
const rightArray = arr.filter((integer) => {
  if (callback(integer)) {
    leftArray.push(integer);
    return false;
  }
  return true;
});
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