简体   繁体   中英

Filtering undefined from array of objects in Javascript

I am having trouble sorting out the undefined from the array of objects that was crated from local storage. Lets assume that this array of of objects is localStorage:

var arrObject = [{date: undefined, bus_name: Thomas #1};...] Assume this has 2 dates that had undefined.

I want to be able to filter out the date that has undefined and the bus_name that is within the date so for example, if I used filter for an array of objects before sorting them, then {date: undefined, bus_name: Thomas #1} will not be included in the array that will be sorted.

How would I accomplish this?

Thanks!

UPDATE: 3/5/20

How would I accomplish this if I have more than 2 columns, lets say I have at least 5, I want to filter and sort date as well as only output date and bus_name

var arrObject = [{date: undefined, bus_name: Thomas #1, bus_driver: Thomas, time_start: 9AM, time_end: 5PM};...]

Output: {date: ..., bus_name:...}; {...} {date: ..., bus_name:...}; {...}

i think you should provide filter with condation field (one is date, another is bus_name )

anyway i want clear it out that :--

 i) arrObject.filter(e => e.date)  // with this all {date: undefined } contain object will be filter and get data which have actual date value 

 ii) arrObject.filter(e => e.date === undefined) // give filter result with all date undefined  
iii) arrObject.filter(e => e.date === undefined && e.bus_name ) or arrObject.filter(e => e.date && e.bus_name)

which one of the result you are expecting

You can use this method:

 const arrObject = [ {date: undefined, bus_name: 'Thomas #1'}, {date: '2012-02-11', bus_name: 'Thomas #2'}, {date: '2012-02-02', bus_name: 'Thomas #3'}, {date: '2012-02-04', bus_name: 'Thomas #4'}, {date: undefined, bus_name: 'Thomas #5'}, {date: '2012-02-03', bus_name: 'Thomas #6'}, {date: '2012-02-03', bus_name: 'Thomas #7'}, ] function formatTheDate (str){ //your format here let FormatedDate = "new Date format" + str return FormatedDate } let newArray = arrObject.filter( obj => { obj.formattedDate = formatTheDate(obj.date) //behave same as obj.date != undefined return obj.date }).sort((a,b)=>{ return Date.parse(a.date) - Date.parse(b.date) }) console.log(newArray);


EDIT: updated the answer to return sorted result based on the date;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM