The filter function is not functioning properly within the Wherefore art thou exercise on Freecodecamp

I'm currently working on a challenge that requires:


Create a function that scans through an array of objects (first parameter) and returns an array containing objects that match the property and value pairs specified in the second parameter. For an object to be included in the result, it must have all the property-value pairs present in the source object.


My attempt at solving this is as follows:

function whatIsInAName(collection, source) {
  var arr = [];
  var srcKeys = Object.keys(source);

  arr = collection.filter(function(obj) {
    for (var i = 0; i < srcKeys.length; i++) {
      return obj.hasOwnProperty(srcKeys[i]) || obj[srcKeys[i]] == source[srcKeys[i]];
    }
  });

  return arr;
}

whatIsInAName([
  { first: "Romeo", last: "Montague" }, 
  { first: "Mercutio", last: null }, 
  { first: "Tybalt", last: "Capulet" }], { last: "Capulet" });

However, my implementation returns an empty array. I suspect I may not fully understand how the filter method works.

One proposed solution is as follows:

function whatIsInAName(collection, source) {
  var srcKeys = Object.keys(source);

  return collection.filter(function (obj) {
    for(var i = 0; i < srcKeys.length; i++) {
      if (!obj.hasOwnProperty(srcKeys[i]) || obj[srcKeys[i]] !== source[srcKeys[i]]) {
        return false;
      }
    }

    return true;
  });
}

// test here
whatIsInAName([
  { first: "Romeo", last: "Montague" }, 
  { first: "Mercutio", last: null }, 
  { first: "Tybalt", last: "Capulet" }], { last: "Capulet" });

I would appreciate a detailed explanation to help clarify why my approach doesn't yield the same output as the provided answer. Thank you for your assistance!

Your help is greatly appreciated.

Answer №1

Two mistakes have been identified in your code.

Initially, in the for loop, there is a comparison of i to the array rather than array.length.

for (var i = 0;i < srcKeys;i++) {

should be

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

Secondly, your filter function presents the opposite of the correct solution. The correct answer only returns true if the item contains the key and its value matches the source. Conversely, your filter function returns true when the item lacks the key or possesses it, with matching values between the item and source, covering all items in this scenario.

return obj.hasOwnProperty(srcKeys[i]) || obj[srcKeys[i]] ==  source[srcKeys[i]];

should actually be

return obj.hasOwnProperty(srcKeys[i]) && obj[srcKeys[i]] ==  source[srcKeys[i]];

Answer №2

Understanding how the filter function works (you can check out Array.prototype.filter) can help you identify errors (like the typo you made, using srcKeys instead of srcKeys.length). When the filter function is used on an array, its callback function is executed for each object in the array. The purpose of this callback is to evaluate each object based on a condition, returning true if the test is successful and false if it's not.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error occurred while binding 'this' in a React onChange event handler

So I've been working on this REACT code that should function properly: App.jsx: class App extends Component { constructor(props){ super(props); this.state = {count: props.initialCount}; this.onChange = this.o ...

Working with arrays of JSON objects in an Android application

Having difficulty with parsing JSON data. I am looking to extract the following information: "jean": { "color": "red", "cost": 15000, "size": 28 } I need to fetch this data from a specific URL and display it in a l ...

What is the best approach to comparing two times in JavaScript to ensure accuracy after an NTP time update?

We are facing an issue with a JavaScript function that retrieves the start and end times of two events: var startTime = new Date().getTime(); // A lengthy task is executed var endTime = new Date().getTime(); The problem we encountered is that getTime() s ...

Save a customized JavaScript file and integrate it into a Vue component

As a newcomer to Vue.js, I have a question regarding calling functions from a custom JavaScript file within a Vue component. Here is what I attempted: custom.js class API{ function testCall(){ alert("test ok"); } } export {API} App.vue ...

Using JQuery to attach a click event to a div element

My HTML code looks something like this: <div class="vmail vmail-bar normal-vmail-bar" id="pm_<?php echo $pm->to_id; ?>"> <div class="checkbox"><input type="checkbox" class="checkbox" /></div> ...

Using AngularJS $http to retrieve data from an ExpressJS endpoint: A comprehensive guide

Here is an example of an ExpressJS route: var exec = require('child_process').exec; app.get('/someURL', function (req, res) { exec('cp file1 file2', (err, stdout, stderr) => { if (err) { // node co ...

Easy method to detect duplicates within an array of strings? (PHP)

My dilemma arises from having an array that contains values like $somearray = array('car','bike','legs,'car'). What I wish to achieve is identifying which values in the array are repeated and determining their respective ...

Replicating a website to use at a later time

I am brand new to the world of Javascript, currently diving into JavaScript and jQuery for an issue I'm facing. Here's what I'm trying to accomplish: I have a selection of words ("foo", "bar") Retrieve the current webpage's content ( ...

Steps for adjusting the structure of an array of objects according to the ParentID

I need to reorganize an array of objects based on a field called ParentID. Here is an example dataset: var JsonVal = "data": { "Factorid": 197325, "orders": [ { ...

Discovering the value of an item when the editItem function is triggered in jsGrid

Within my jsGrid setup, I have invoked the editItem function in this manner: editItem: function(item) { var $row = this.rowByItem(item); if ($row.length) { console.log('$row: '+JSON ...

Deploying Node.js on a server

So I have successfully installed Node.js on my server. However, despite researching for hours, I am still confused about the next steps. I have not been able to find a clear explanation of what I need to do next. On my local machine, I can easily run Nod ...

Avoid inputting numbers and special characters

In my coding work, I have crafted a function that detects the key pressed by the user through an event. NameValidation(e){ if(!e.key.match(/^[a-zA-Z]*$/)) { e.key = ''; console.log(e.key); } }, This function essentia ...

Obtaining information from node.js module to the server.js script

I am attempting to extract data from a function within a node module, which returns a JSON object. My goal is to display this JSON object in a router located in my server.js file. This is how I am trying to export it: // Function Export exports.g ...

How do I retrieve the top position of the text content itself, not the text element, using jQuery or Javascript?

I'm facing a unique challenge and need some guidance: I am trying to determine the exact y-coordinate of specific text in a document. Simply getting the y-coordinate of the container element is not sufficient for my needs. To illustrate this issue, p ...

On a button click, the div's height will increase and then decrease when the same button is clicked again

I need help with a div that has its height set to 0px initially, and I want it to increase to 300px when a button is clicked. When the button is clicked again, I want the height to go back to 0px. Here's the CSS code: nav{ height:0px; overfl ...

Is there a way to properly dissect or iterate through this?

I have exhausted all possible methods to retrieve the data, but I am unable to solve this puzzle. The information is organized in a format like the following: [{"code":1000,"day":"Sunny","night":"Clear","icon":113,"languages": [{"lang_name":"Arabic","lan ...

Encountering an error when using JSONP with a period in the callback function

I am currently facing an issue with making an ajax jsonp call. It seems that the json returned contains a dot in the callback function, as shown in the example below: ABCD.render_section({ "page": { "parameters": { "pubDate": "2013-06-05 00:00:00.0", ...

Determine the date 7 days before today using JavaScript

I've been trying to calculate the date that is 12 days before today's date, but I'm running into an issue where it's not returning the correct result. For instance, if today is November 11, 2013 (mm/dd/yyyy), the code returns October 30 ...

Sending Arrays to PHP Extension

I am facing a challenge in passing two arrays from PHP to a C extension module that has been compiled with the PHP source code. One array will contain integers while the other will consist of strings. While I have some understanding of both PHP and C, navi ...

Integrating JSON back into the system

As I work with Axios to retrieve information from an API, I am able to successfully connect and receive an object with the necessary data. However, I am struggling to display this JSON data in my HTML code. Here is the code snippet I am using: <body&g ...