-3

I have my array of object "messages" i want to calculate the number of items that have "seen:1"

const messages = [ 

 { id: 66, seen:1, tourist_full_name: "Khouloud Ben Abddallah" },
 { id: 102, seen: 0, tourist_full_name: "Harry Paz Galvez" },
{ id: 103, seen: 0, tourist_full_name: "Harry Paz Galvez" },
 { id: 104, seen: 1, tourist_full_name: "Harry Paz Galvez" },
{ id: 105, seen: 1, tourist_full_name: "Harry Paz Galvez" }
];

for example here i want to create a variable that can be like this

var SeenCount=3 ;

how can i do that ?

Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
mariemHel
  • 21
  • 3

1 Answers1

1

Use the reduce function to increment based on the seen property of each object. Our default value is 0 and it will increment in each iteration of our loop depending on the seen property value

const messages = [ 

 { id: 66, seen:1, tourist_full_name: "Khouloud Ben Abddallah" },
 { id: 102, seen: 0, tourist_full_name: "Harry Paz Galvez" },
{ id: 103, seen: 0, tourist_full_name: "Harry Paz Galvez" },
 { id: 104, seen: 1, tourist_full_name: "Harry Paz Galvez" },
{ id: 105, seen: 1, tourist_full_name: "Harry Paz Galvez" }
];


let a = messages.reduce((acc, item) => {
  return acc + item.seen;
}, 0);

console.log(a);
chevybow
  • 9,959
  • 6
  • 24
  • 39