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

122
Visualizações
Count duplicates in a 2D Array and create a new 2D Array and expand it with the counts

I have a 2d this array with few values. I want to count the duplicates in this array and get a new 2d array with the values and in the end the number of counts

let colors = [
  ['blue', 'green', 5.00, 57],
  ['blue', 'green', 5.00, 57],
  ['yellow', 'green', 8.30, 84],
  ['blue', 'green', 5.00, 57],
  ['orange', 'blue', 7.00, 0],
  ['yellow', 'green', 8.30, 84],
];

function count_duplicate() {
  let counts = []
  for (let i = 0; i < colors.length; i++) {
    if (counts[colors[i]]) {
      counts[colors[i]] += 1
    } else {
      counts[colors[i]] = 1
    }
  }
  console.log(counts);
}

count_duplicate();

now ich have this result

counts = [blue,green,5,57: 3, yellow,green,8.3,84: 2, orange,blue,7,0: 1]

but i need the array like this

counts = [[blue,green,5,57,3],
          [yellow,green,8.3,84,2],
          [orange,blue,7,0,1]]
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You can use Map here to achieve the result:

let colors = [
  ["blue", "green", 5.0, 57],
  ["blue", "green", 5.0, 57],
  ["yellow", "green", 8.3, 84],
  ["blue", "green", 5.0, 57],
  ["orange", "blue", 7.0, 0],
  ["yellow", "green", 8.3, 84],
];

function count_duplicate() {
  let counts = new Map();

  for (let i = 0; i < colors.length; i++) {
    const data = counts.get(colors[i].toString());
    if (data) data.count++;
    else counts.set(colors[i].toString(), { value: colors[i], count: 1 });
  }

  const result = [];
  for (let [, { value, count }] of counts) {
    result.push([...value, count]);
  }
  return result;
}

console.log(count_duplicate());

about 4 years ago · Juan Pablo Isaza Relatório

0

change from array [] to an object {}, to easly manipulate each sub-array(row) how many times occures, it should be an object not an array! and Using Object.entries looping through its key(str) and value(times), and return str splitted by comma and their times of occurences.

let colors = [
  ["blue", "green", 5.0, 57],
  ["blue", "green", 5.0, 57],
  ["yellow", "green", 8.3, 84],
  ["blue", "green", 5.0, 57],
  ["orange", "blue", 7.0, 0],
  ["yellow", "green", 8.3, 84],
];

function count_duplicate() {
  let counts = {};//<-- 
  for (let i = 0; i < colors.length; i++) {
    if (counts[colors[i]]) {
      counts[colors[i]] += 1;
    } else {
      counts[colors[i]] = 1;
    }
  }
 console.log(counts); //{ 'blue,green,5,57': 3, 'yellow,green,8.3,84': 2, 'orange,blue,7,0': 1 }
  const res = Object.entries(counts).map((count) => {
    [str, times] = count; //['blue,green,5,57': 3]
    return [...str.split(","), times];//[ 'blue', 'green', '5', '57', 3 ]
  });
  console.log(res);
}
count_duplicate();

Result:

[ [ 'blue', 'green', '5', '57', 3 ],
  [ 'yellow', 'green', '8.3', '84', 2 ],
  [ 'orange', 'blue', '7', '0', 1 ] ]
about 4 years ago · Juan Pablo Isaza Relatório

0

I don't know about fancy syntax but using a hashmap should work which is just a JavaScript object.

let colors = [
        ['blue', 'green', 5.00, 57],
        ['blue', 'green', 5.00, 57],
        ['yellow', 'green', 8.30, 84],
        ['blue', 'green', 5.00, 57],
        ['orange', 'blue', 7.00, 0],
        ['yellow', 'green', 8.30, 84],
       
];

const hashmap = {};

colors.forEach(color => {
    const key = JSON.stringify(color);
    if(!hashmap[key]) hashmap[key] = 1;
    else hashmap[key]++;
    if(hashmap[key] == 1) return color;
});

console.log(hashmap);

const uniqueArray = [];

for(const key in hashmap) 
    uniqueArray.push(JSON.parse(key));

console.log(uniqueArray);

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