2

I want to show the total number of Likes using only pure JS. I grabbed the numbers from the JSON file but I don't know how to get the Total number of likes, I tried to use reduce method it didn't work maybe i am doing in the wron way

This is what I want to do click here for the photo This is my code

function photographerWork(JsonData, homeElement){
   const homeElt = homeElement.id;
   JsonData.media.forEach(element => {   
   if(homeElt == element.photographerId){
       const domDiv = document.getElementById('photographer-work');
       const newDiv = document.createElement("div");
       /////  the code i'am trying  ////
       const allTheLiks = element.likes
       console.log(allTheLiks)
       //////////////////////
       const workTemplate = `         
           <div class="photo-box"> 
               <div class="photo">
                   ${videoOrImage(element.image, element.video, element)}
               </div>   
               <div class="text">
                   <p> ${element.tags}<b>${element.price} €  &nbsp ${element.likes} <i class="fas fa-heart"></i></b></p>
               </div>
           </div>
           `
       newDiv.innerHTML = workTemplate;
       domDiv.appendChild(newDiv);
       likesAndPrice(element, allTheLiks); 
     }
 })
} 

This is my Result click hereenter code here

This is my JSON file example

 "media": [
      {
        "id": 342550,
        "photographerId": 82,
        "image": "../Photos/Tracy/Fashion_Yellow_Beach.jpg",
        "tags": ["fashion"],
        "likes": 62,
        "date": "2011-12-08",
        "price": 55
      },
      {
        "id": 8520927,
        "photographerId": 82,
        "image": "../Photos/Tracy/Fashion_Urban_Jungle.jpg",
        "tags": ["fashion"],
        "likes": 11,
        "date": "2011-11-06",
        "price": 55
      },
      {
        "id": 9025895,
        "photographerId": 82,
        "image": "../Photos/Tracy/Fashion_Pattern_on_Pattern.jpg",
        "tags": ["fashion"],
        "likes": 72,
        "date": "2013-08-12",
        "price": 55
      },
      {
        "id": 9275938,
        "photographerId": 82,
        "image": "../Photos/Tracy/Event_WeddingGazebo.jpg",
        "tags": ["events"],
        "likes": 69,
        "date": "2018-02-22",
        "price": 55
      },
      {
        "id": 2053494,
        "photographerId": 82,
        "image": "../Photos/Tracy/Event_Sparklers.jpg",
        "tags": ["events"],
        "likes": 2,
        "date": "2020-05-25",
        "price": 55
      },
Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
deveb2020
  • 101
  • 2
  • 9
  • 1
    sum them up in the loop – Aalexander Jan 26 '21 at 18:05
  • Hi! @EgzonBerisha I have something going on. I will add the answer soon. But just to confirm what is the reduce formulation you have done till now? – Rohan Asokan Jan 26 '21 at 18:09
  • 1
    Does this answer your question? [Sum of array object property values in new array of objects in Javascript](https://stackoverflow.com/questions/37481539/sum-of-array-object-property-values-in-new-array-of-objects-in-javascript) – Heretic Monkey Jan 26 '21 at 18:10
  • NOTE TO POTENTIAL ANSWERERS: This question, and questions like it, are asked with relatively high frequency on Stack Overflow. So often does this happen, we have several canonical duplicates. Please at least do a cursory search for duplicate before answering the question. – Heretic Monkey Jan 26 '21 at 18:14
  • @EgzonBerisha I have offered a one liner answer to the problem - took me hours to figure. hope it helps – Rohan Asokan Jan 26 '21 at 18:16

4 Answers4

1

Before you enter the forEach() create a local variable sum

let sum = 0;

Then inside your forEach() do the following

sum += element.likes;

Then when the loop has finished in sum will be the total amount of likes.

Updated code.

function photographerWork(JsonData, homeElement){
   let sum = 0;
   const homeElt = homeElement.id;
   JsonData.media.forEach(element => {   
   if(homeElt == element.photographerId){
       const domDiv = document.getElementById('photographer-work');
       const newDiv = document.createElement("div");
       /////  the code i'am trying  ////
       const allTheLiks = element.likes
       console.log(allTheLiks)
       //////////////////////

       sum += element.price;

       const workTemplate = `         
           <div class="photo-box"> 
               <div class="photo">
                   ${videoOrImage(element.image, element.video, element)}
               </div>   
               <div class="text">
                   <p> ${element.tags}<b>${element.price} €  &nbsp ${element.likes} <i class="fas fa-heart"></i></b></p>
               </div>
           </div>
           `
       newDiv.innerHTML = workTemplate;
       domDiv.appendChild(newDiv);
       likesAndPrice(element, allTheLiks); 
     }

})
 // here you have the sum now 
    console.log(sum);
} 
Aalexander
  • 4,987
  • 3
  • 11
  • 34
  • Hi Alex, thank you very much this actually worked, my problem was not knowing where to position elements inside the loop or outside, thank you man, is it possible to use the result inside a template literale in another function ? – deveb2020 Jan 26 '21 at 18:37
  • 1
    You're welcome @EgzonBerisha :) Sure you can pass it as a parameter to another function and there you can most likely use it as template literale. *Not familiar with template literale* where the console log is you can call your function with sum as parameter `yourfunction(sum)` – Aalexander Jan 26 '21 at 18:41
1

const media = [{
    "id": 342550,
    "photographerId": 82,
    "image": "../Photos/Tracy/Fashion_Yellow_Beach.jpg",
    "tags": ["fashion"],
    "likes": 62,
    "date": "2011-12-08",
    "price": 55
  },
  {
    "id": 8520927,
    "photographerId": 82,
    "image": "../Photos/Tracy/Fashion_Urban_Jungle.jpg",
    "tags": ["fashion"],
    "likes": 11,
    "date": "2011-11-06",
    "price": 55
  },
  {
    "id": 9025895,
    "photographerId": 82,
    "image": "../Photos/Tracy/Fashion_Pattern_on_Pattern.jpg",
    "tags": ["fashion"],
    "likes": 72,
    "date": "2013-08-12",
    "price": 55
  },
  {
    "id": 9275938,
    "photographerId": 82,
    "image": "../Photos/Tracy/Event_WeddingGazebo.jpg",
    "tags": ["events"],
    "likes": 69,
    "date": "2018-02-22",
    "price": 55
  },
  {
    "id": 2053494,
    "photographerId": 82,
    "image": "../Photos/Tracy/Event_Sparklers.jpg",
    "tags": ["events"],
    "likes": 2,
    "date": "2020-05-25",
    "price": 55
  }
];

const response = media.reduce((total, { likes }) => {
  total += likes;
  return total;
}, 0);

console.log(`total likes: ${response}`);

you can use reduce function and do something like that:

const response = media.reduce((total, { likes }) => {
  total += likes;
  return total;
}, 0);
Kidas
  • 319
  • 2
  • 11
0

Assuming jsonData to be the variable holding your data.

var totalLikes =  jsonData.media.reduce((acc, cur) => (true, {likes: acc.likes + cur.likes})).likes

A great one liner to do the task. There are two ways - one that @Kidas has posted and mine - which just reduces in such a way that a JSON object is maintained throughout the reduce and the later accessing that. If you don't like to use the ES6 syntax - just replace the arrow function with a function

var totalLikes =  jsonData.media.reduce(function (acc, cur) {
    return (true, {likes: acc.likes + cur.likes})
}).likes
Rohan Asokan
  • 634
  • 4
  • 22
0

You need to add the likes eachtime you render a card(i.e: object). I have added a variable combinedLikes and adding the likes each time.

cheers :)

function photographerWork(JsonData, homeElement){
   const homeElt = homeElement.id;
   let combinedLikes = 0;
   JsonData.media.forEach(element => {   
   if(homeElt == element.photographerId){
       const domDiv = document.getElementById('photographer-work');
       const newDiv = document.createElement("div");
       /////  the code i'am trying  ////
       combinedLikes += element.likes;
       console.log(allTheLiks)
       //////////////////////
       const workTemplate = `         
           <div class="photo-box"> 
               <div class="photo">
                   ${videoOrImage(element.image, element.video, element)}
               </div>   
               <div class="text">
                   <p> ${element.tags}<b>${element.price} €  &nbsp ${element.likes} <i class="fas fa-heart"></i></b></p>
               </div>
           </div>
           `
       newDiv.innerHTML = workTemplate;
       domDiv.appendChild(newDiv);
       likesAndPrice(element, combinedLikes); 
     }
 })
} 
PatelManas
  • 102
  • 4