Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to remove element in array object

array :
array before
[ { id: 1, test: [ null, 2, 3 ] }, { id: 2, test: [ 1, 2, 3 ] } ]

array after
[ { id: 1, test: [ 2, 3 ] }, { id: 2, test: [ 1, 2, 3 ] } ]
how to remove value null?

I have tried with this function but it doesn’t work what is wrong with this functionl in array?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var filtered = fullArray.filter(function (object) {
    return object.test !== null;
  });

>Solution :

In JavaScript, the Array.filter() method can be used to remove elements from an array based on a condition. In your case, you can use Array.filter() to remove null values from the test array of each object in the input array. Here’s a possible implementation:

function removeNullValues(array) {
  return array.map(obj => {
    obj.test = obj.test.filter(val => val !== null);
    return obj;
  });
}

The function takes an array of objects as input, where each object has an id property and a test property that is an array containing null values. The function returns a new array of objects, where the test array of each object no longer contains null values.

The Array.map() method is used to iterate over each object in the input array and return a new object with the filtered test array. The Array.filter() method is used to remove null values from the test array of each object. The arrow function val => val !== null is used as the filter function, which returns true for all values that are not null.

You can call the function like this:

const array = [
  { id: 1, test: [null, 2, 3] },
  { id: 2, test: [1, 2, 3] }
];

const result = removeNullValues(array);

console.log(result);
// Output: [ { id: 1, test: [ 2, 3 ] }, { id: 2, test: [ 1, 2, 3 ] } ]

This should give you the desired output.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading