Remove empty elements from an array in Javascript
EDIT: This question was answered almost nine years ago when there were not many useful built-in methods in the Array.prototype
.
Now, certainly, I would recommend you to use the filter
method.
Take in mind that this method will return you a new array with the elements that pass the criteria of the callback function you provide to it.
For example, if you want to remove null
or undefined
values:
var array = [0, 1, null, 2, "", 3, undefined, 3,,,,,, 4,, 4,, 5,, 6,,,,];
var filtered = array.filter(function (el) { return el != null;});
console.log(filtered);
Remove empty array elements
As you're dealing with an array of strings, you can simply use array_filter()
, which conveniently handles all this for you:
print_r(array_filter($linksArray));
Keep in mind that if no callback is supplied, all entries of array equal to FALSE
(see converting to boolean) will be removed. So if you need to preserve elements that are i.e. exact string '0'
, you will need a custom callback:
// PHP 7.4 and later
print_r(array_filter($linksArray, fn($value) => !is_null($value) && $value !== ''));
// PHP 5.3 and later
print_r(array_filter($linksArray, function($value) { return !is_null($value) && $value !== ''; }));
// PHP < 5.3
print_r(array_filter($linksArray, create_function('$value', 'return $value !== "";')));
Note: If you need to reindex the array after removing the empty elements, use: $linksArray = array_values(array_filter($linksArray));
How do I remove null values from an array within an array?
I know I can run through each array and delete the empties... thats pretty much your only options. There are methods that make your code look cleaner but behind the scenes something is going to have to loop through the array.
Here is an example using Array.map()
and Array.filter()
let data = [["bob", , ], ["jake", "john", ""], ["joe", "henry", "morgan"]];let newData = data.map(x => { return x.filter(j => j)})console.log(newData);
How to remove null values from nested arrays
If your array-of-arrays only has one level, then you can just map
it like this:
var filtered = array.map(subarray => subarray.filter(el => el != null));
console.log(filtered);
How to remove the null values from an array containing multiple arrays in javascript?
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);
What is the most efficient method to remove null values within an array.
Yes, your method's time complexity is O(n)
- your loop has n
(the length of the array) iterations, and copying an array requires time proportional to the size of the copied array, which in this case is O(n)
in the worst case.
And you can't do better than that (in terms of time complexity), since you have to iterate over the entire array in order to locate the elements that should be removed.
If your goal is to reduce code complexity (i.e. write the shortest amount of code), you can use an IntStream
(requires Java 8 or later):
public static int[] removeNull(int[] array) {
return Arrays.stream(array).filter(i -> i != 0).toArray();
}
As Andreas commented, this solution has the advantage of leaving the original array unchanged.
How to remove null value in array of objects using reduce?
can you please try this,
I did add an additional loop to remove the null or empty string of key,
you can improve it as needed though
const generated_salary = [{"f_name":"Cy","deduction":{"11":{"amount":736,"wrk_pay_id":11}}},{"f_name":"Hel","deduction":{"10":{"amount":714.29,"wrk_pay_id":10},"14":{"amount":500,"wrk_pay_id":14}}},{"f_name":"edd","deduction":{"13":{"amount":857.14,"wrk_pay_id":13}}},{"f_name":"JAY","deduction":{"":{"amount":"","wrk_pay_id":""}}}]
const deductions = generated_salary.reduce((c, { deduction }) => {
return ({
...c,
...deduction
})
}, {})
Object.keys(deductions).map((key) => {
if (key === null || key === '') delete deductions[key]
})
console.info("deductions =", deductions)
Related Topics
How to Extract or Uncompress Gzip File Using PHP
How to Iterate Through Dom Elements in PHP
Prevent Session Expired in PHP Session for Inactive User
Declaring a Global Variable Inside a Function
Time Calculation in PHP (Add 10 Hours)
Laravel: General Error: 1615 Prepared Statement Needs to Be Re-Prepared
Set Character Set Using MySQLi
How to Use Composer to Autoload Classes from Outside the Vendor
Connecting to Websocket with PHP Client
How to Protect HTML Form from Spammers
How to Replace the Text of a Node Using Domdocument
What Does a PHP Function Return by Default
How to Convert Float Value to Integer in PHP