Skip to content

Instantly share code, notes, and snippets.

@codebubb
Last active January 10, 2024 12:56
Show Gist options
  • Save codebubb/2c2b247c5d7de6df03d87f9458c4ecc0 to your computer and use it in GitHub Desktop.
Save codebubb/2c2b247c5d7de6df03d87f9458c4ecc0 to your computer and use it in GitHub Desktop.
Array of People
const people = [
{ firstName: 'Sam', lastName: 'Hughes', DOB: '07/07/1978', department: 'Development', salary: '45000' },
{ firstName: 'Terri', lastName: 'Bishop', DOB: '02/04/1989', department: 'Development', salary: '35000' },
{ firstName: 'Jar', lastName: 'Burke', DOB: '11/01/1985', department: 'Marketing', salary: '38000' },
{ firstName: 'Julio', lastName: 'Miller', DOB: '12/07/1991', department: 'Sales', salary: '40000' },
{ firstName: 'Chester', lastName: 'Flores', DOB: '03/15/1988', department: 'Development', salary: '41000' },
{ firstName: 'Madison', lastName: 'Marshall', DOB: '09/22/1980', department: 'Sales', salary: '32000' },
{ firstName: 'Ava', lastName: 'Pena', DOB: '11/02/1986', department: 'Development', salary: '38000' },
{ firstName: 'Gabriella', lastName: 'Steward', DOB: '08/26/1994', department: 'Marketing', salary: '46000' },
{ firstName: 'Charles', lastName: 'Campbell', DOB: '09/04/1977', department: 'Sales', salary: '42000' },
{ firstName: 'Tiffany', lastName: 'Lambert', DOB: '05/11/1990', department: 'Development', salary: '34000' },
{ firstName: 'Antonio', lastName: 'Gonzalez', DOB: '03/24/1985', department: 'Office Management', salary: '49000' },
{ firstName: 'Aaron', lastName: 'Garrett', DOB: '09/04/1985', department: 'Development', salary: '39000' },
];
// Exercises
// 1) What is the average income of all the people in the array?
// 2) Who are the people that are currently older than 30?
// 3) Get a list of the people's full name (firstName and lastName).
// 4) Get a list of people in the array ordered from youngest to oldest.
// 5) How many people are there in each department?
@siccoo
Copy link

siccoo commented Jun 26, 2020

//Exercise 4

var youngest = people[0]; var oldest = people[0]; people.forEach(function(person) { if (youngest.DOB < person.DOB) { youngest = person; } if (person.DOB < oldest.DOB) { oldest = person; } }); console.log(youngest, oldest);

@siccoo
Copy link

siccoo commented Jun 26, 2020

//Exercise 4
var youngest = people[0]; var oldest = people[0]; people.forEach(function(person) { if (youngest.DOB < person.DOB) { youngest = person; } if (person.DOB < oldest.DOB) { oldest = person; } }); console.log(youngest, oldest);

@siccoo
Copy link

siccoo commented Jun 27, 2020

// Exercise 4 Using the forLoop method

`
let youngestToOldest = people[0];

for(let i = 0; i < people.length; i++) {
    for(let j = 0; j < people.length; j++) {
        if(people[i].age < people[j].age) {
            let youngestToOldest = people[i]; // store the original position in array so we can swap it
            people[i] = people[j]; // move up the original position in array
            people[j] = youngestToOldest; // set to youngestToOldest (complete the swap)
        }
    }
}
 console.log(youngestToOldest);

`

@hed911
Copy link

hed911 commented Nov 13, 2020

// Exercise 1
const average = people.reduce((a, i) => a + parseInt(i.salary), 0) / (people.length + 0.0);

@hed911
Copy link

hed911 commented Nov 13, 2020

// Exercise 2

const getAge = (dateString) => {
    var today = new Date();
    var birthDate = new Date(dateString);
    var age = today.getFullYear() - birthDate.getFullYear();
    var m = today.getMonth() - birthDate.getMonth();
    if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
        age--;
    }
    return age;
}
const olderThan30 = people.filter( e => getAge(e.DOB) > 30);

@hed911
Copy link

hed911 commented Nov 13, 2020

//Exercise 3
const list = people.map( e => ${e.firstName} ${e.lastName})

@hed911
Copy link

hed911 commented Nov 13, 2020

// Exercise 4

const getAge = (dateString) => {
    var today = new Date();
    var birthDate = new Date(dateString);
    var age = today.getFullYear() - birthDate.getFullYear();
    var m = today.getMonth() - birthDate.getMonth();
    if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
        age--;
    }
    return age;
}
const list = people.map((e) => {
    e.age = getAge(e.DOB);
    return e;
}).sort((a,b) => a.age - b.age)

@hed911
Copy link

hed911 commented Nov 13, 2020

//Exercise 5
let departments = {};

people.forEach((e) => {
    if(departments[e.department] == null)
        departments[e.department] = 0;
    departments[e.department] += 1;
})

@dalmia01
Copy link

dalmia01 commented Nov 21, 2020

// Exercises

// 1) What is the average income of all the people in the array?
/** find average */
const average = (arr) => arr.reduce((acc, curr) => acc + curr, 0) / arr.length;

const peoplesSalariesArray = people.map((item) => +item.salary);
console.log("Average of peoples income --> ", average(peoplesSalariesArray));

// 2) Who are the people that are currently older than 30?
const basedonSomeCondition = (arr, fn) => {
let someArr = [];
arr.forEach((item) => {
if (fn(new Date().getFullYear() - item.DOB.split("/")[2])) {
someArr.push(item);
}
});
return someArr;
};

console.log(
"People older than 30 --> ",
basedonSomeCondition(people, (x) => x > 30)
);

//or

const filterBasedOnCondition = people.filter((item) => new Date().getFullYear() - item.DOB.split("/")[2] > 40);
console.log("People older than 30 --> ", filterBasedOnCondition);

// 3) Get a list of the people's full name (firstName and lastName).

const peoplesFullName = people.map((item) => ${item.firstName} ${item.lastName});
console.log("Peoples Full Name --> ", peoplesFullName);

// 4) Get a list of people in the array ordered from youngest to oldest.
const getDate = (str) => new Date(str.split("/")[2], str.split("/")[0], str.split("/")[1]);

const youngestToOldest = people.sort((a, b) => (new Date() - getDate(a.DOB) > new Date() - getDate(b.DOB) ? 1 : -1));

console.log("Youngest to oldest --> ", youngestToOldest);

// 5) How many people are there in each department?

const eachDepartement = people.reduce(
(acc, curr) => (acc[curr.department] ? { ...acc, [curr.department]: acc[curr.department] + 1 } : { ...acc, [curr.department]: 1 }),
{}
);

console.log("Each Departement peoples --> ", eachDepartement);

@needlzzz
Copy link

Exercise 1:

let totalSalary = 0;
for (i = 0; i < people.length; i++) {
totalSalary += parseInt(people[i]['salary'])

}
console.log("Average Salaray: ", totalSalary / people.length)

Exercise 3:

for (i = 0; i < people.length; i++) {
let firstName = people[i]['firstName'];
let lastName = people[i]['lastName'];
console.log(firstName + ' ' + lastName)
}

Exercise 5:

let developmentDepartment = [];
let marketingDepartment = [];
let salesDepartment = [];
let officeMgmtDepartment = [];

for (i = 0; i < people.length; i++) {

let departmentName = people[i]['department'];
if (departmentName === 'Development') {
    developmentDepartment.push(departmentName)

}
if (departmentName === 'Marketing') {
    marketingDepartment.push(departmentName);
}
if (departmentName === 'Sales') {
    salesDepartment.push(departmentName);

}
if (departmentName === 'Office Management') {
    officeMgmtDepartment.push(departmentName);
}

}
console.log('Development: ', developmentDepartment.length)
console.log('Marketing: ', marketingDepartment.length)
console.log('Sales: ', salesDepartment.length)
console.log('Office Mgmt: ', officeMgmtDepartment.length)

@AbirHal
Copy link

AbirHal commented Jun 17, 2021

// Exercise 4 Using the forLoop method

`
let youngestToOldest = people[0];

for(let i = 0; i < people.length; i++) {
    for(let j = 0; j < people.length; j++) {
        if(people[i].age < people[j].age) {
            let youngestToOldest = people[i]; // store the original position in array so we can swap it
            people[i] = people[j]; // move up the original position in array
            people[j] = youngestToOldest; // set to youngestToOldest (complete the swap)
        }
    }
}
 console.log(youngestToOldest);

`

it's fault

@karan11-code
Copy link

karan11-code commented Jun 29, 2021

1 exercise solution
var income = people.map(inc => parseInt(inc.salary));
var avgIncome = income.reduce((a, b) => { return a + b })/income.length
console.log(avgIncome);

@salAhamad
Copy link

salAhamad commented Oct 17, 2021

Question No.: 1 ( What is the average income of all the people in the array? )

With reduce (ES6)
const averageSalary = people.reduce((total, person) => total + parseInt(person.salary) / people.length, 0);
console.log(averageSalary);
With for loop
const averageSalaryTwo = () => {
   let total = 0;
   for(let i=0; i < people.length; i++) {
       total = total + parseInt(people[i].salary);
   }
   return total / people.length;
}
console.log(averageSalary2());
With forEach loop
const averageSalaryThree = () => {
    let total = 0;
    officePeople.forEach(person => total += parseInt(person.salary));
    return total / officePeople.length;
}
console.log(averageSalaryThree());

Question No.: 2 ( Who are the people that are currently older than 30? )

With filter (ES6)
const olderThanThirty = people.filter(person => new Date().getFullYear() - new Date(person.DOB).getFullYear() > 30)
console.table(olderThanThirty);
const olderThan30 = [];
for(let i = 0; i < people.length; i++) {
    if((new Date().getFullYear() - new Date(people[i].DOB).getFullYear()) > 30 ) {
        olderThan30.push(people[i])
    }
}
console.table(olderThan30);
With forEach loop
people.forEach(person => {
    if((new Date().getFullYear() - new Date(person.DOB).getFullYear()) > 30) olderThan30.push(person);
});
console.table(olderThan30);

Question No.: 3 ( Get a list of the people's full name (firstName and lastName) )

With Map (ES6)
const fullName = people.map(({firstName, lastName}) => `${firstName} ${lastName}`)
console.table(fullName);
With For Loop
const fullName2 = [];
for(i=0; i < people.length; i++) {
    fullName2.push(`${people[i].firstName} ${people[i].lastName}`)
}
console.table(fullName2);
With ForEach Loop
const fullName3 = [];
people.forEach(person => {
    fullName3.push(`${person.firstName} ${person.lastName}`)
});
console.table(fullName3);

Question No.: 4 ( Get a list of people in the array ordered from youngest to oldest )

const oldest = people.sort((a, b) => new Date(a.DOB) - new Date(b.DOB) ? 1 : -1)
console.table(oldest);

Question No.: 5 ( How many people are there in each department? )

const departments= {};
people.forEach(person => 
    !departments[person.department] ?  departments[person.department] = 1 
    : departments[person.department] += 1);

console.table(departments);

@emirhansisman
Copy link

1) What is the average income of all the people in the array?
const avgIncome = people.reduce( (avg, person, i, people) => Number((avg + person.salary / people.length).toFixed()), 0 );

2) Who are the people that are currently older than 30?
const olderThan30 = people.filter( (person) => new Date(Date.now()).getFullYear() - new Date(person.DOB).getFullYear() > 30 );

3) Get a list of the people's full name (firstName and lastName).
const peopleFullName = people.map( (person) => ${person.firstName} ${person.lastName} );

4) Get a list of people in the array ordered from youngest to oldest.
const sortByAgeAsc = people.sort((a, b) => new Date(b.DOB) - new Date(a.DOB));

5) How many people are there in each department?

const peopleCountInDepts = people.reduce((counts, people, i, arr) => {
counts.has(people.department)
? counts.set(people.department, counts.get(people.department) + 1)
: counts.set(people.department, 1);
return counts;
}, new Map());

@webdevoliva123
Copy link

let salary = 0;
let total = people.length;
let num = people.map((e,i,a) => {
salary = salary + (+e.salary);
});
let avg = salary/total;
console.log(average income of all pepople is ${avg});

@Sunny-123456
Copy link

//exercise 3
for(let a=0;a<people.length;a++){
let b =people[a].firstName;
let c = people[a].lastName;
let d = b+" "+c;
console.log(d);
}

@Anilgya
Copy link

Anilgya commented Apr 24, 2023

// exercise 1

let a=people.map(function(value, index){
return value.salary
})
let sum=a.map(function(value){
return parseInt(value)
})
let sum1=sum.reduce(function(value, index){
return value+index
})

console.log(sum1/(people.length))

@rnura1234
Copy link

// 1) What is the average income of all the people in the array?
const averageIncome=(arr)=>{
let totalIncomeOfAlltheEmployee=0;
let totalEmployee=arr.length
for(let i=0;i<arr.length;i++){
totalIncomeOfAlltheEmployee+=arr[i].salary*1;
}
console.log(totalIncomeOfAlltheEmployee)
return totalIncomeOfAlltheEmployee/totalEmployee

}

console.log(averageIncome(people))

// 2) Who are the people that are currently older than 30?
const oldThan30=(arr)=>{
const d=new Date();
const yy=d.getFullYear();
return arr.filter(item=> yy-item.DOB.split('/')[2]>30)
}
console.log(oldThan30(people))

// 3) Get a list of the people's full name (firstName and lastName).

const peopleFullName=people.map(item=>${item.firstName} ${item.lastName})
console.log(peopleFullName)

// 4) Get a list of people in the array ordered from youngest to oldest.

const sortPeopleByAge=(arr)=>{
return arr.sort((a,b)=>new Date(a.DOB)-new Date(b.DOB))
}
console.log(sortPeopleByAge(people))

// 5) How many people are there in each department?

const numberOfPeaopeInDepartment=(people)=>{
let obj={}
for(let i=0;i<people.length;i++){
if(obj[people[i].department]){
obj[people[i].department]+=1
}else{
obj[people[i].department]=1
}
}
return obj
}
console.log(numberOfPeaopeInDepartment(people))

@anshdeshwal
Copy link

for question 2
const olderThirty = (p = people) => {
const currentDate = new Date();
const thirtyYearsAgo = currentDate.getFullYear() - 30;

let a = p.filter((person) => {
    const dob = new Date(person.DOB);
    const dobYear = dob.getFullYear();
    const dobMonth = dob.getMonth() + 1;
    const dobDay = dob.getDate();
    return (dobYear < thirtyYearsAgo) || (dobYear === thirtyYearsAgo && dobMonth < currentDate.getMonth() + 1) || (dobYear === thirtyYearsAgo && dobMonth === currentDate.getMonth() + 1 && dobDay <= currentDate.getDate());
});
return a;

};
console.log(olderThirty());

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment