How come the filter function produces different results compared to using push with a for..of loop?

After extracting an array of objects from the raw data provided in this link, I have encountered a dataset that resembles the following:

[0 ... 99] 0 : city : "New York" growth_from_2000_to_2013 : "4.8%" latitude : 40.7127837 longitude : -74.0059413 population : "8405837" rank : "1" state : "New York" proto : Object 1 : {city: "Los Angeles", growth_from_2000_to_2013: "4.8%", latitude: 34.0522342, longitude: -118.2436849, population: "3884307", ...}

This dataset is stored as const JSON_LOCS, referenced in the code below.

I am attempting to filter this dataset to find cities that contain specific text. I've tried two different approaches. One method seems to be successful, while the other involving Array.prototype.filter() does not seem to work.

const test = [];
      for (let t of JSON_LOCS) {
        if (t.city.includes('las')) {
          test.push(t);
        }
      }

      const test2 = JSON_LOCS.filter(loc => { // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
        loc.city.includes('las');
      });
      console.log(test); // Outputs a few results
      console.log(test2); // Always empty! :(

Answer №1

Make sure to include the return statement in your code like this:

return oc.city.includes('las');

By adding the return statement, you ensure that the correct value is returned instead of undefined.

Answer №2

Get rid of the { }

const test2 = JSON_LOCS.filter(loc => { // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
  loc.city.includes('las');
});

change to

const test2 = JSON_LOCS.filter(loc => // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
  loc.city.includes('las'); // When not enclosed in {}, it is assumed as the return statement
);

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

Could you explain the meaning of int **p?

I'm struggling to understand how pointers work when referencing an array of pointers in dynamic memory. Specifically, I am wondering how this concept applies to the stack. Does using a pointer create an array of pointers on the stack that point to th ...

The issue of ExpressionChangedAfterItHasBeenCheckedError is a common problem faced by Angular

I have implemented a component loading and an interceptor to handle all requests in my application. The loading component is displayed on the screen until the request is completed. However, I am encountering an error whenever the component inside my router ...

Is there a way for me to showcase the latitude and longitude retrieved from JSON data on a Google Map using modals for each search result in Vue.js?

After receiving JSON data with search results, each containing latitude and longitude coordinates, I am attempting to display markers on a Google map modal when clicking "View Map". However, the code I'm using is not producing the desired outcome. Th ...

Guide on transforming a collection of files from formdata into a JavaScript object

I have a dataset containing multiple images associated with the same product id. import client from "@/lib/fetchWrapper"; export default async function addProductImage({ photo, productId, }: { photo: File[]; productId: string; }) { if ...

I need to search through a tree structure in typescript based on a specific value without encountering a maximum stack call exceeded error

How can I perform a value-based search on a complex tree structure in TypeScript without encountering the maximum stack call exceeded error? I am attempting to navigate through an expandable tree using TypeScript, and I will provide the code snippet below ...

Enabling onClick based on conditions

I'm struggling to disable a Link onClick when a certain condition is not met. Attempted to move the logic outside of render using a function, but the button always ends up disabled. Tried CSS to disable click, only to realize that tab and enter can ...

What is the best way to extract message data using discord.js?

Discord.js is an API designed for developers to create plugins for Discord, a popular communication platform. You can find the API code written in JavaScript by visiting https://github.com/hydrabolt/discord.js/ On Discord, users interact on servers where ...

Error: Python is raising a TypeError because you are trying to iterate over a 0

I've been working on a basic nearest neighbor calculation and I'm running into some issues. When trying to retrieve the value of 't', I encountered a type error. Upon attempting to return only 't', the function showed an empty ...

"How to ensure consistent styling for all buttons, including dynamically created ones, in an application by utilizing the jQuery button widget without the need for repetitive calls to

Hello everyone, I am a newcomer to stack overflow and I have a question to ask. Please excuse any errors in my query. I have searched for an answer but have not been successful in finding one so far. Let's say I have a webpage where I am using the jQ ...

Changing a JSON Array of Objects into a List of Strings

I am currently working on extracting data from JSON and converting it into a Java ArrayList. String query = "SELECT attributes FROM common_attr_test"; PreparedStatement preparedStatement = (PreparedStatement) conn.prepareStatement(query); preparedStatemen ...

Enhancing user experience with dynamic search results: JQuery AutoComplete powered by XML

As a newcomer to AJAX, JavaScript, and the web, I'm struggling with understanding this concept. When using JQuery's autocomplete feature with a small flat file of limited items (suggestions.xml), everything works perfectly. However, when switchin ...

It is not feasible to establish a personalized encoding while sending a post request through XMLHTTPRequest

When using the JS console in the latest version of Chrome browser, I encountered the following issue: x = new XMLHttpRequest(); x.open('POST', '?a=2'); x.setRequestHeader('Content-Type', 'application/ ...

What is the best way to sort an array based on a person's name?

I have a list of different groups and their members: [ { "label": "Group A", "fields": [ { "value": "color1", "name": "Mike" }, { &quo ...

D3.js: Unveiling the Extraordinary Tales

I'm currently working on a project that requires me to develop a unique legend featuring two text values. While I have successfully created a legend and other components, I am facing difficulties in achieving the desired design. Specifically, the cur ...

A table featuring an HTML select element that allows users to choose from preset options or manually enter

My goal is to incorporate a select box where users can either choose from a set list of options or input their own custom value. The select element is nested within a table. Unfortunately, using datalist is not a viable solution for me in this case. I have ...

What are some tips for using copy and paste with Protractor on a Mac using Chrome?

Is there a way to utilize copy and paste functionality with Protractor on a MAC using Chrome? newInput.sendKeys(protractor.Key.chord(browser.controlKey, "a")); newInput.sendKeys(protractor.Key.chord(browser.controlKey, "c")); newInput.sendKeys(protractor. ...

Angular does not delay for promises to settle

Issue I am facing is related to Angular not waiting for promises to be resolved. The console inspection reveals that the provider and skills objects are not retrieved before the promises are returned. I have included the key parts of the code below. The s ...

Issue encountered while executing npm command: "Module 'npmlog' not found"

Today marks the beginning of my first job, and as I was setting up my development environment on my Mac (OSX) by updating node and npm, something went awry. Whenever I attempt to use npm in my command line (npm init, npm install, etc.), I am confronted wit ...

Best practices for logging error objects in JavaScript

As a beginner in web development, I've recently come across an interesting observation related to handling errors. When working with json.stringyfy(), I noticed that the message key is not displayed in statement 2. However, accessing error.message ret ...

What is the best practice for adding one string to the end of another?

So, is this the best way to concatenate strings in JavaScript? var str = 'Hello'; str += ' World'; While most languages allow for this method of string concatenation, some consider it less efficient. Many programming languages offer a ...