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

93
Visualizações
Build a new array from two other arrays in Javascript

I have two arrays:

alphabet is composed of letters (e.g. the English alphabet). dictionary is a list of objects with words and definitions, 'word' being the key for the word value.

I want to build a new array called frequency which would contain the number of words that start with each letter in the alphabet array, with indices corresponding to the alphabet array.

I've managed to come up with the following:

alphabet.forEach(function(letter) {
        frequency = dictionary.filter(item => item['word'].toLowerCase().startsWith(letter)).length;
    });

This gets me individual values for frequency. What is the best syntax in Javascript for building an array of those values? Is it another filter? Or should the code use the current forEach manually with a incremental index?

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

0

Using reduce, you can easily make a new object with the letter as the key and an array of matches as the value.

const words = ["abba", "ant", "apple", "bannana", "barn", "car", "cat"];

const alphabet = "abcdefghijklmnopqrstuvwxyz".split("");

const result = alphabet.reduce((a, letter) => {
  a[letter] = words.filter(word => word.toLowerCase().startsWith(letter));
  return a;
}, {});

console.log(result);

about 4 years ago · Juan Pablo Isaza Relatório

0

First, let's get some example data. We'll ignore anything that isn't related to the question.

const alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('')
var dictionary = [{'word': 'alpha'}, {'word': 'beta'}, {'word': 'balloon'}]

Then we'll create a results variable, which will hold an array of all results in alphabetical order.

var results = []

Now we loop over the same way you did before, but we'll push each result to our list.

alphabet.forEach(function(letter) {
  frequency = dictionary.filter(item => item['word'].toLowerCase().startsWith(letter)).length;
  results.push(frequency);
});

As an alternative solution that allows us to more easily look through our results, we'll make results an object, and use letters as keys.

var results = {};
alphabet.forEach(function(letter) {
  frequency = dictionary.filter(item => item['word'].toLowerCase().startsWith(letter)).length;
  results[letter] = frequency;
});
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