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?
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.