How to remove an array of filtered objects in Javascript

After following the reference link, I successfully implemented sorting and column functionality. However, there are two remaining tasks that I require assistance with.

Firstly, I need to customize the names of the columns according to my preference (e.g., changing 'date' to 'Date' and 'bus_name' to 'busName').

Secondly, I want to eliminate filtered arrays. Although I found a solution that worked, it also removed empty strings at the end of the array. My goal is to remove any empty strings or undefined values from the array without impacting the original mapped array.

This was the initial accepted answer provided:

var array = [{ date: " ", bus_name: 'Thomas #1', driver_name: 'Sam', time_start: '9AM', time_end: '5PM' }, { date: '2012-02-11', bus_name: 'Thomas #2', driver_name: 'Samantha', time_start: '8AM', time_end: '4PM' }, { date: '2011-02-02', bus_name: 'Thomas #3', driver_name: 'Peter', time_start: '12PM', time_end: '7PM' }, { date: '2010-06-04', bus_name: 'Thomas #4', driver_name: 'Eddie', time_start: '11AM', time_end: '6PM' }, { date: " ", bus_name: 'Thomas #5', driver_name: 'Raul', time_start: '4AM', time_end: '1PM' }, { date: '2014-04-03', bus_name: 'Thomas #6', driver_name: 'Jessie', time_start: '5AM', time_end: '2PM' }], result = array .filter(o => o.date !== ' ') .map(({ date, bus_name }) => ({ date, bus_name })) .sort((a, b) => a.date.localeCompare(b.date));

console.log(result);

In regards to filtering, I aim to exclude ' ', 0, or undefined values from the mapped array. I am looking for guidance on incorporating this modification while maintaining the structure established by the accepted answer mentioned earlier. The array in question is stored in localStorage.

Please refer to the guidelines specified in the linked resource below!

Access the reference here: Filtering undefined or empty strings from array of objects in Javascript

Answer №1

To optimize the code:

  • Ensure that the variable o.date is not falsy (such as null, undefined, false, 0, or an empty string) by including o.date &&
  • Instead of using the ES6 shorthand, utilize a complete object literal to assign alternative names for the properties and adjust the sort function accordingly

var array = [{ date: " ", bus_name: 'Thomas #1', driver_name: 'Sam', time_start: '9AM', time_end: '5PM' }, { date: '2012-02-11', bus_name: 'Thomas #2', driver_name: 'Samantha', time_start: '8AM', time_end: '4PM' }, { date: '2011-02-02', bus_name: 'Thomas #3', driver_name: 'Peter', time_start: '12PM', time_end: '7PM' }, { date: '2010-06-04', bus_name: 'Thomas #4', driver_name: 'Eddie', time_start: '11AM', time_end: '6PM' }, { date: " ", bus_name: 'Thomas #5', driver_name: 'Raul', time_start: '4AM', time_end: '1PM' }, { date: '2014-04-03', bus_name: 'Thomas #6', driver_name: 'Jessie', time_start: '5AM', time_end: '2PM' }],
    result = array
        .filter(o => o.date && o.date !== ' ')
        .map(({ date, bus_name }) => ({ arrival: date, busName: bus_name }))
        .sort((a, b) => a.arrival.localeCompare(b.arrival));

console.log(result);

Note: I chose to use arrival as the property name because starting a name with a capital letter (like Date) is not commonly seen -- typically, initial capitals are reserved for constructors or classes.

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

What is the most efficient method for arranging the numbers in a whole number?

Is there a more efficient method than storing the numbers in an array and using .sort() to arrange them? ...

Detecting button clicks in different views using Backbone.js

In my current setup, I have a main parent view called View.A which is responsible for managing two child views - View.B and View.C. Specifically, View.B contains buttons that trigger events on that view. Configuration View.A View.B view.B.template. ...

When using WYSIWYG editors, be on the lookout for empty paragraphs and incorrect code in CSS, JavaScript, and

I am currently in the process of redesigning a website for a client. The site is already built using Joomla 1.7, but I am facing an issue with the articles section that was created by the client using a WYSIWYG editor. The problem lies in the messy code st ...

Is it possible to use regex for matching both spaces and letters exclusively?

I recently created a regular expression that only allows letters. While I'm not very experienced with regex, I am struggling to figure out how to also include spaces in my expression. This is the HTML code I have: <input id="input" /> Below i ...

Several external JavaScript files all containing variables with identical names

My project involves showcasing noise measurement data from various locations on a website. The data is collected using sound level meter devices at each location, read through a windows-based application, and uploaded to a web server as a .js file with an ...

Show temporary information on the user's side in a table

To better explain the issue, please refer to the accompanying image. I am working with a Master/Detail form, specifically a Bill of Materials, which involves storing data in two separate database tables. The top portion of the form (Product, Quantity) is ...

Create an array of dynamically calculated properties from the Vuex state array, which can then be utilized in the v-model

In my Vue 3 setup, I have a Vuex store with an array in the state: const store = createStore({ state: { questions: [ { text: 'A', value: false }, { text: 'B', value: false }, { text: 'C', value: true }, ...

AngularJS does not hide the Onsen UI modal

I am new to working with angularjs and onsen ui. I have implemented a modal in an ajax request, which is supposed to hide upon successful response. Everything seems to be working fine, except for the fact that when I navigate back to the page, the modal re ...

Creating a personalized validation tool using regular expressions in AngularJS version 2.2.4

Let me present the challenge at hand: I am currently working on developing a "custom validator" for password and email fields using AngularJS v2. The structure of my project involves multiple files interacting with each other: /forms/form.component.ts / ...

What is the process of assigning a value to a form in Angular 4?

I have some data that I need to insert into a form. Currently, I am using reactive forms in Angular 6. Check out the Demo Application: In my list of items, each item has an edit button. When this button is clicked, it triggers the edit component. My goa ...

Could someone share an instance of an AngularJS configuration that continuously checks for new data and automatically refreshes the user interface once the data is obtained?

Struggling to find a suitable example for this scenario. I am looking to create a chart directive that will be updated every minute by fetching data from a web service. Currently, I have a service that acts as a wrapper for the web service. My controller ...

Mastering the flow of control in Node.js programs

Attempting to grasp control flow within Node.js applications. Specifically, does control loop back to the original function once the callback method completes, similar to a callback stack in recursive calls? A simple program was crafted to make a GET call ...

Certain styling properties in React Native can sometimes prevent a view from being rendered

Greetings! I am new to React Native and currently working on developing an Android app using this technology. I have encountered an issue where changing the style of my view (such as backgroundColor or borderBottom) prevents it from rendering properly. Des ...

Loading pointers into an array from a file using C

I need help with reading data that is formatted using fprintf(fp,"%s %s %s\n", p->name,p->surname,p->tc);. I have created a struct patients **p in the following way: struct patients **create_array(struct patients **ptr,int length){ int i; ...

Display the outline of a translucent image

Looking to create an image reveal effect on my website. I want to display only the outline of a transparent image using brightness, then gradually reveal the full image by removing the brightness effect. Currently, I achieve this with a black outline usi ...

Utilizing the map function to modify the attributes of objects within an array

I have a data structure with unique IDs and corresponding status keys. My goal is to count how many times each status repeats itself. Here's an example of my data structure: const items = { id: 2, status_a: 1, status_b: 1, status_c: 3 }; Below is the ...

A guide to creating a JavaScript API

I'm keen on developing an API that allows other websites to access data from my web application. Despite searching online, I haven't found any helpful resources explaining the process of creating a custom JavaScript API. I am interested in unde ...

Tips on preserving type safety after compiling TypeScript to JavaScript

TS code : function myFunction(value:number) { console.log(value); } JS code, post-compilation: function myFunction(value) { console.log(value); } Are there methods to uphold type safety even after the conversion from TypeScript to JavaScript? ...

Error: The signature for uploading S3 Knox Node.js does not match

For the past several days, I've been attempting to upload a file named message.txt to AWS S3 using knox and node js. However, I continuously encounter an error stating that the signature doesn't match. Here is my code snippet in node js (since ...

Converting Wordpress custom field data into an array within a query output

I decided to create a unique field called "sec1array" within my categories to store an array of numbers such as 1,2,3,4 To retrieve and display this array within a loop, I wrote the following code: $seconearray = array($cat_data['sec1array']); ...