HAJJI
HAJJI

Reputation: 1

JavaScript Filtering

I am trying to build a filter that filters an array based on qualification and years of experience among other criteria after clicking the filtering button, I am new to JavaScript and as such I have encountered many challenges. I've had a challenge incorporating a function for the button that filters the array and returns the desired output. Ideas on how best I can implement this and have fully functioning code will be highly appreciated.

<!DOCTYPE html>
<html>

<head>
  <meta charset="utf-8">
  <title>APPLICANT FILTERING</title>
</head>

<body>
  <h1>FILTER APPLICANTS</h1>
  <button onclick="newArray()">CLICK TO FILTER</button>
  <p id="demo"></p>

  <script>
    var obj = {
        'applicants': [{
            "name": "Tom",
            "qualification": "degree",
            "experience": 5}, {
              "name": "David",
              "qualification": "certificate",
              "experience": 2},
          ]
        };
        var newArray = obj.applicants.filter(function(el) {
          return el.qualification = 'degree' &&
            el.experience >= 5;
        });
        console.log(newArray);
        document.getElementById("demo").innerHTML = text;
  </script>
</body>

</html>

Upvotes: 0

Views: 91

Answers (1)

Isaac Jandalala
Isaac Jandalala

Reputation: 318

This should work. In your object, experience is a string (e.g. "5 years"). Instead, you should consider using integer values for this (i.e. 5) because the second expression in your filter (el.experience >= 5) expects a numeric value for experience.

const obj = {
    'applicants': [{
        "name": "Tom",
        "qualification": "degree",
        "experience": 5,
    }, {
        "name": "David",
        "qualification": "certificate",
        "experience": 2
    }, ]
};
const newArray = obj.applicants.filter((el) => (
    el.qualification == 'degree' && el.experience >= 5
));
console.log(newArray);

Upvotes: 2

Related Questions