Home > Software design >  Retrieve information from object JS
Retrieve information from object JS

Time:11-06

  1. Find the person who has many skills in the users object.

  2. Count logged in users, count users having greater than equal to 50 points from the following object

const users = {
  Alex: {
    email: '[email protected]',
    skills: ['HTML', 'CSS', 'JavaScript'],
    age: 20,
    isLoggedIn: false,
    points: 30
  },
  Asab: {
    email: '[email protected]',
    skills: ['HTML', 'CSS', 'JavaScript', 'Redux', 'MongoDB', 'Express', 'React', 'Node'],
    age: 25,
    isLoggedIn: false,
    points: 50
  },
  Brook: {
    email: '[email protected]',
    skills: ['HTML', 'CSS', 'JavaScript', 'React', 'Redux'],
    age: 30,
    isLoggedIn: true,
    points: 50
  },
  Daniel: {
    email: '[email protected]',
    skills: ['HTML', 'CSS', 'JavaScript', 'Python'],
    age: 20,
    isLoggedIn: false,
    points: 40
  },
  John: {
    email: '[email protected]',
    skills: ['HTML', 'CSS', 'JavaScript', 'React', 'Redux', 'Node.js'],
    age: 20,
    isLoggedIn: true,
    points: 50
  },
  Thomas: {
    email: '[email protected]',
    skills: ['HTML', 'CSS', 'JavaScript', 'React'],
    age: 20,
    isLoggedIn: false,
    points: 40
  },
  Paul: {
    email: '[email protected]',
    skills: ['HTML', 'CSS', 'JavaScript', 'MongoDB', 'Express', 'React', 'Node'],
    age: 20,
    isLoggedIn: false,
    points: 40
  }

Why do I get stuck when solving this kind of problem with arrays and objects? I have done so many projects with the front end(Angular), but can't solve this, I know the logic but am not able to put it in code. please help, need advice on how to get better, do I need to learn Algorithms to get better at this kind of problems?

CodePudding user response:

This is how you can get the person who has many skills in the users object

    const compareFn = (a, b) => {

      if(a[1]?.skills?.length < b[1]?.skills?.length) return 1
      return -1
    }

    const array = Object.entries(users);
    const sortedArray = array.sort(compareFn);

    const person = sortedArray[0][0]; //the name of person person who has many skills
    const personValues = sortedArray[0][1]; //the values of person person who has many skills


    const [personName, personValues] = sortedArray[0]; //get the name and values of person

    const sortedObject = Object.fromEntries(sortedArray) //Returns a sorted object

The techniques used in this solution

function compareFn(a, b) {
  if (a is less than b by some ordering criterion) {
    return -1;
  }
  if (a is greater than b by the ordering criterion) {
    return 1;
  }
  // a must be equal to b
  return 0;
}
  • Related