Search Object Array value

Asked

Viewed 62 times

1

I have following Object:

let Filmes = [{
                "Nome": "Harry Potter 1",
                "Preco": "50"
             },
             {
                "Nome": "Harry Potter 2",
                "Preco": "60"
             },
             {
                "Nome": "Harry Potter 3",
                "Preco": "70"
             }] 

let Cliente = ["Harry Potter 1", "Harry Potter 3"]
let ValorFinal = ""

How I do using the array Cliente to verify in which Filmes the Cliente want? And after doing this, return me the Preco of the movie. The output of this would be:

Final value = 120

Because the Client wants the Harry Potter 1 and Harry Potter 3.

If possible in vanilla JS please

2 answers

8


It is possible to use the methods filter and reduce.

let filmes = [{
                "Nome": "Harry Potter 1",
                "Preco": "50"
             },
             {
                "Nome": "Harry Potter 2",
                "Preco": "60"
             },
             {
                "Nome": "Harry Potter 3",
                "Preco": "70"
             }];

let cliente = ["Harry Potter 1", "Harry Potter 3"];

const valor = filmes.filter((f) => cliente.includes(f.Nome)) // Filtra pelos escolhidos
    .reduce((a, b) => a + parseFloat(b.Preco), 0); // Soma o valor dos escolhidos

console.log(valor);

  • Perfect! These Filter, Reduce and Map methods are a bit tricky. But they are extremely useful!

1

I believe that this iteration will bring the expected result:

var valorFinal = 0;

for (i = 0; i < Filmes.length; i++) {
    for (j = 0; j < Cliente.length; j++) {
        if (Cliente[j] == Filmes[i]["Nome"]) {
            valorFinal += Filmes[i]["Preco];
            break;
        }
    }
}
  • 1

    This works perfectly too, but I opted for the other answer to be easier to read :) . Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.