0

I have an array that consists of a list of arrays. I want to delete the null elements from my array. The below picture is the array. What I want is if the date is null, then the whole part with the value should be removed from the array.

Original Array = [
   [[value:null, data:Alcohol],[value:null, data:null]],
   [[value:Test, date:Wed],[value:Test2, date:null]],
   [[value:Test3, date:null],[value:Test4, date:Wed]],
   [[value:Test5, date:Wed],[value:Test6, date:null]]
];

Final Array ​= [
  ​[[value:null, data:Alcohol]],
  ​[[value:Test, date:Wed]],
  ​[[value:Test3, date:null]],
  ​[[value:Test5, date:Wed]]
];

The original Array

The original Array

After removing the null values, I need it to be like the below image.

The array show be after

The array show be after

3
  • 1
    Could you parse the actual json here so everyone can use it to help you better? Anyway, an Array.map() function would do it. Commented Aug 10, 2021 at 6:54
  • Can you post the example array in code instead of a screenshot? Commented Aug 10, 2021 at 6:57
  • 1
    Could you please provide the data as actual valid JS code? Commented Aug 10, 2021 at 7:05

3 Answers 3

3

You could map the outer array to a new array, and use a filter on the nested/inner arrays to filter out elements with a null date property.

const newData = data.map(el => el.filter(({ date }) => date !== null));

const data = [
   [{value:null, data:'Alcohol'},{value:null, data:null}],
   [{value:'Test', date:'Wed'},{value:'Test2', date:null}],
   [{value:'Test3', date:null},{value:'Test4', date:'Wed'}],
   [{value:'Test5', date:'Wed'},{value:'Test6', date:null}]
]

const newData = data.map(el => el.filter(({ date }) => date !== null));

console.log(newData);

Sign up to request clarification or add additional context in comments.

1 Comment

@ParulRanjan Is it not already? 😉 Are there specific objects you are referring to?
2

Something like a filter into a map:

yourArray.map(x => x.filter(y => y.date !== null))

Comments

0

const array = [1, 2, null, 4, null, 6]
const filtered = array.filter(item => item !== null)
console.log(filtered)

3 Comments

You don't actually need to check if item !== null. You can just return item :)
@Wimanicesir unless you don't want to filter out falsy items that aren't null
Yeah but there are more situations where you do want to also filter them out than the other way around :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.