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

147
Visualizações
Pushing unique element in an 2D array from another 2D array

I am trying to do this challenge in FCC, inventory update.

Only problem I am facing is that, when I want to push the new element from the new array to the old array, it is giving me timeout. Adding the numbers if the element matches works fine though. Here is what I have done so far.

//sorting the 2D array
function sortingArray(a,b){
    if (a[1] === b[1]) {
        return 0;
    }
    else {
        return (a[1] < b[1]) ? -1 : 1;
    }
}

function updateInventory(arr1, arr2) {
    if (arr1.length === 0) {
        return arr2.sort(sortingArray)
    }
    if (arr2.length === 0) {
        return arr1.sort(sortingArray)
    }
    for (let i = 0; i < arr2.length; i++) {
        for (let j = 0; j < arr1.length; j++) {
            if (arr2[i][1] === arr1[j][1]) {
                arr1[j][0] = arr1[j][0] + arr2[i][0] //adding the numbers if it matches
            }
            if(arr2[i][1] != arr1[j][1]){
                arr1.push(arr2[i]) //pushing the unique element
            }
            
        }
    }
    console.log(arr1)
    return arr1.sort(sortingArray);
}

// Example inventory lists
var curInv = [[21, "Bowling Ball"], [2, "Dirty Sock"], [1, "Hair Pin"], [5, "Microphone"]];

var newInv = [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]];

updateInventory(curInv, newInv);
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You are not checking the uniqueness of each element when adding to the curInv.

For i = 0, you are checking the items [21, "Bowling Ball"] with [2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]

Thus when [21, "Bowling Ball"] is compared [2, "Hair Pin"] this element is being added to the curInv, because their second element are not equal to each other. And the same thing happens for [3, "Half-Eaten Apple"], [7, "Toothpaste"]

Now when i = 1, you are checking the items [2, "Dirty Sock"] with [2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]

Here when [2, "Dirty Sock"] is compared to [2, "Hair Pin"] or the other elements, they are added to the curInv again. It is wrong because these elements already exists from the first iteration(i=0) and hence you are not checking the uniqueness of the elements.

This also resulted in the increasing size of curInv beyond what you intended.

Try using some other data structure or using some different algorithm and then construct the resulting array.

about 4 years ago · Juan Pablo Isaza Relatório

0

You can significantly reduce lines and complexity of perception if use objects as temporary data storage. For example:

const curInv = [[21, "Bowling Ball"],[2, "Dirty Sock"],[1, "Hair Pin"],[5, "Microphone"]];
const newInv = [[2, "Hair Pin"],[3, "Half-Eaten Apple"],[67, "Bowling Ball"],[7, "Toothpaste"]];

const rev = (item) => item.reverse();

function updateInventory(arr1, arr2) {
  const obj1 = Object.fromEntries(arr1.map(rev));
  const obj2 = Object.fromEntries(arr2.map(rev));
  const mergedObj = Object.entries(obj2)
    .reduce((acc, [name, count]) => ({
      ...acc,
      [name]: acc[name] ? acc[name] += count : count
    }), obj1);
  return Object.entries(mergedObj)
    .sort(([a], [b]) => a.localeCompare(b))
    .map(rev);
};

console.log(updateInventory(curInv, newInv));
.as-console-wrapper{min-height: 100%!important; top: 0}

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