how to loop through an array of objects in javascript and get objest with highest count code example

Example 1: javascript loop through object example

var person={
 	first_name:"johnny",
  	last_name: "johnson",
	phone:"703-3424-1111"
};
for (var property in person) {
  	console.log(property,":",person[property]);
}

Example 2: javascript loop through array of objects

let arr = [object0, object1, object2];

for (let elm of arr) {
  console.log(elm);
}

Example 3: js loop over array of objects extract value

var myArr = [{name: 'rich', secondName: 'james'}, {name: 'brian', secondName: 'chris'}];

var mySecondArr = myArr.map(x => x.name);
console.log(mySecondArr);

Example 4: js loop array of objects

// Array of objects
const p = [{
  "p1": "value1",
  "p2": "value2",
  "p3": "value3"
},
{
  "p4": "value4",
  "p5": "value5",
  "p6": "value6"
}];

// Get the objects out of the array
for (let obj of p) {
  // console.log(obj);
  // output: 
  // { p1: 'value1', p2: 'value2', p3: 'value3' }
  // { p4: 'value4', p5: 'value5', p6: 'value6' }
  // Now we can loop the objects in the array by nesting the 'for in' loop inside the 'for of' loop
  for(let key in obj) {
    console.log(key);
    // output:
    // p1
    // p2
    // p3
    // p4
    // p5
    // p6
    // console.log(obj[key]);
    // output
    // value1
    // value2
    // value3
    // value4
    // value5
    // value6
  }
}

Example 5: loop array of objects

const myArray = [{x:100}, {x:200}, {x:300}];

const newArray= myArray.map(element => {
    return {
        ...element,
        x: element.x * 2
    };
});

console.log(myArray); // [100, 200, 300]
console.log(newArray); // [200, 400, 600]

Example 6: iterate over array of objects javascript

// Count the number of each category

const people = [
    {name: 'John', group: 'A'}, 
    {name: 'Andrew', group: 'C'}, 
    {name: 'Peter', group: 'A'}, 
    {name: 'James', group: 'B'}, 
    {name: 'Hanna', group: 'A'}, 
    {name: 'Adam', group: 'B'}];

const groupInfo = people.reduce((groups, person) => {
    const {A = 0, B = 0, C = 0} = groups;
    if (person.group === 'A') {
        return {...groups, A: A + 1};
    } else if (person.group === 'B') {
        return {...groups, B: B + 1};
    } else {
        return {...groups, C: C + 1};
    }
}, {});

console.log(groupInfo); // {A: 3, C: 1, B: 2}