How to remove false values from array? - javascript

I receive this in console
0: false
1: false
2: false
3: false
4: false
5: "scuole"
6: "scuole"
7: "scuole"
8: "scuole"
I need to remove all false and I have been trying to follow this on SO
and I tried
var scuole = [];
function bouncer(scuole) {
return scuole.filter(item => item);
}
bouncer([false, null, 0, NaN, undefined, ""]);
console.log(scuole);
But I still see false in console

Check comments for explaination.
var scuole = []
function bouncer(scuole) {
// .filter returns a new filtered array and in following case
// filtered array will return an array whos value is
// not equal to false
return scuole.filter(item => item !== false);
}
//when calling bouncer function which returns an array
// we need to store that returned array to scuole variable
// for future use.
scuole = bouncer([false, null, 0, NaN, undefined, ""]);
// expected result [ null, 0, NaN, undefined, ""]
console.log(scuole);

Array.filter returns a new array, so you would have to assign it to a new variable. Also you currently do not filter, you dont process the item. Try this:
var someArray = [true, true, false, true];
function bouncer(array) {
return array.filter(item => item !== false);
}
var otherArray = bouncer(someArray);
// expected output: [true, true, true]
Have a look at the documentation

You can use Boolean to cleanup all falsy values of an array.
const cleaned = [false, null, 0, NaN, undefined, ""].filter(Boolean);
// return "[]"

You can just use the "filter" function of JavaScript which will return you the filtered array. Please note, the filter will not update the original array hence you need to catch filtered array in a different array.
According to the snippet, I am returning the values except false. Let me know if you have any other issues or doubts.
var original_arr = [false, null, 0, NaN, undefined, ""]
var filtered_arr = original_arr.filter(function(item){return item != false})
console.log(filtered_arr);

var scuole = [false, null, 0, NaN, undefined, ""];
scuole= scuole.filter(item =>item!=false ||item!='false');
console.log(scuole);
you can do like this...

This should work:
const arr = [ false, null, NaN, 0, undefined, true, 'string', 1, 'text', 4.3, ''];
const newArr = arr.filter(e => e)
Should print out: [ true, 'string', 1, 'text', 4.3 ]

Related

I only need the 0 value in this case from an array of [0, undefined, null, false]

I have tried the filter and find method to get the value 0 but it did not worked it just returns undefined
[0, undefined, null, false].filter(e => e) // output empty array
[0, undefined, null, false].find(e => e) // output undefined
If anybody helps me out to find the solution for this I would greatfull for you help
const filtered = [0, undefined, null, false].filter(e => e === 0);
const found = [0, undefined, null, false].find(e => e === 0);
console.log(filtered);
console.log(found);

Javascript switch array values from boolean to string

I have this 2 dimensional array =
0: (3) [true, false, false]
1: (3) [true, true, false]
2: (3) [true, true, true]
3: (3) [false, false, false]
The position in the array represents the same in each i.e 0 = "Learner" 1 = "Manager", 2 = "ClientAdmin"
I want a new 2 dimensional array that looks like below
0: (3) ["Learner"]
1: (3) ["Learner", "Manager"]
2: (3) ["Learner", "Manager", "ClientAdmin"]
3: (3) []
I have tried
selectedAudienceMandatoryArrayText = []
this.selectedAudienceMandatoryArray.forEach( (isArray, index) => {
if (isArray[0] == true) {
this.selectedAudienceMandatoryArrayText[index].push("Learner");
}
if (isArray[1] == true) {
this.selectedAudienceMandatoryArrayText[index].push("Manager");
}
if (isArray[2] == true) {
this.selectedAudienceMandatoryArrayText[index].push("ClientAdmin");
}
}
but I get the error: Cannot read property 'push' of undefined
What is the most efficient way to do this. ES6 solutions welcome.
You could check if the flag is set, then take the value from roles with the index or return an empty array.
const
roles = ["Learner", "Manager", "ClientAdmin"],
data = [[true, false, false], [true, true, false], [true, true, true], [false, false, false]],
result = data.map(a => a.flatMap((f, i) => f ? roles[i] : []));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
selectedAudienceMandatoryArrayText = [];
this.selectedAudienceMandatoryArray.forEach(isArray => {
const roles = [];
if (isArray[0]) roles.push('Learner');
if (isArray[1]) roles.push('Manager');
if (isArray[2]) roles.push('ClientAdmin');
selectedAudienceMandatoryArrayText.push(roles);
}
You could push to a new array for each loop, and at the end, push that to the other array. This reduces having to keep track of the index for the outer array.

How to remove null values from nested arrays

This code removes all null values from array:
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);
But when I try this on an array with nested arrays that have null values, the nulls are not removed:
var array = [ [ 1, null, 2 ], [ 3, null, 4 ], [ 5, null, 6 ] ];
var filtered = array.filter(function (el) {
return el != null;
});
console.log(filtered);
The expected output is:
[ [ 1, 2 ], [ 3, 4 ], [ 5, 6 ] ]
Instead of the actual output:
[ [ 1, null, 2 ], [ 3, null, 4 ], [ 5, null, 6 ] ]
How can I change my example to filter null values from the 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);
You need to recursively filter for null, like so:
function removeNull(array) {
return array
.filter(item => item !== null)
.map(item => Array.isArray(item) ? removeNull(item) : item);
}
This function takes an array, and recursively removes all instances of null.
First, I took your solution and wrapped it in a function so that it is able to be called.
Then, after the items are filtered, it's as simple as mapping over the remaining items, checking if each one is an array, and then for each one that is, calling removeNull on it.
EDIT: I had a typo in my code originally, but it should work now.
var arraylist = [0, 1, null, 5];
var i = arraylist.length;
var j =0;
var newlist = [];
while(j < i){
if(arraylist[j] != null){
newlist.push(arraylist[j]);
}
j++;
}
console.log(newlist);
https://jsfiddle.net/L4nmtg75/
var filterFn = function(item) {
if (item instanceof Array) {
// do this if you want to remove empty arrays:
var items = item.splice(0).filter(filterFn);
var length = items.length;
Array.prototype.push.apply(item, items);
return length;
// if you want to keep empty arrays do this:
var items = item.splice(0);
Array.prototype.push.apply(item, items.filter(filterFn))
return true;
}
return item != null;
};
array = array.filter(filterFn);
This will also work on more than 2 level, as it's recursive.
You're examples remove undefined values as well as null values, and your expected output reflects that, so I'm going to assume that you mean you want to recursively remove both undefined and null values. Your example uses a loose equality comparison which means that it will match both null and undefined. While this works, it is much better to be explicit about what you're checking for with strict equality comparison using ===.
You're going to need to use recursion:
Recursion
An act of a function calling itself. Recursion is used to solve problems that contain smaller sub-problems.
- https://developer.mozilla.org/en-US/docs/Glossary/Recursion
This also means that you're going to want to use Array#reduce instead of Array#filter. Use a new array as the accumulator.
Then for each element in the input array where the element is not null or undefined:
if the element is an instance of Array, push the result of calling this function on the element onto the accumulator array,
otherwise push the element onto the accumulator array
Return the accumulator array at the end of the reduce callback as the accumulator
const input = [ [ 1, null, 2 ], null,,,,, [ 3, null, 4 ],,,,, [ 5, null, 6 ],,,,, [ 7, [ 8, undefined, 9 ], 10 ] ]
function recursiveValues(input) {
if(!(input instanceof Array)) return null
return input.reduce((output, element) => {
if(element !== null && element !== undefined) {
if(element instanceof Array) {
output.push(recursiveValues(element))
} else {
output.push(element)
}
}
return output
}, [])
}
const output = recursiveValues(input)
console.log(JSON.stringify(output))

How to convert object to array only if its each value is true

I have selectedSizeList on my state.
selectedSizeList = {1: false, 2: true, 3: true, 4: true, 5: false}
How do I convert my selectedSizeList to this array?
[2, 3, 4]
Do I have better algorithm than this one? (I assume my solution is not correct)
let array = [];
Objects.keys(selectedSizeList).maps((item) => {
if(item.value) array.push(item.value)
);
return array;
You can use array#filter to filter out all keys with true value.
const selectedSizeList = {1: false, 2: true, 3: true, 4: true, 5: false};
const result = Object
.keys(selectedSizeList)
.filter(k => selectedSizeList[k])
.map(Number);
console.log(result);
First of all get the array keys using Object.keys() and then use filter() to filter only the true values like this.
var selectedSizeList = {1: false, 2: true, 3: true, 4: true, 5: false};
var keys = Object.keys(selectedSizeList);
var filtered = keys.filter(function(key) {
return selectedSizeList[key]
});
console.log(filtered);
Try this (O(n) solution):
selectedSizeList = {1: false, 2: true, 3: true, 4: true, 5: false};
var arr = [];
for (var key in selectedSizeList) {
if(selectedSizeList[key]){
arr.push(key);
}
}
console.log(arr);
You could use Object.keys() to return an`array that you can then use Array.prototype.filter() on to return a new array.
selectedSizeList = {1: false, 2: true, 3: true, 4: true, 5: false};
let array = Object.keys(selectedSizeList).filter((item) => {
if(selectedSizeList[item]) return item;
});
//returns [2,3,4]
You can use Object.keys to get an array that you can then filter for values equal to true which will return an array of numbers as a string. You can then map through the array using Number to convert the number strings to numbers which may or may not be necessary depending on what you plan to do with this result. I put this into a function that you can re-use or at least not have your object hard coded with.
var selectedSizeList = {1: false, 2: true, 3: true, 4: true, 5: false};
// Re-usable function not tied to specific object
const filterForTrueValue = (obj) => Object
.keys(obj)
.filter(k => obj[k])
.map(Number);
console.log(filterForTrueValue(selectedSizeList));

Set all Object keys to false

Lets say I have an object
filter: {
"ID": false,
"Name": true,
"Role": false,
"Sector": true,
"Code": false
}
I want to set all keys to false (to reset them). What's the best way to do this, I'd like to avoid looping with foreach and stuff. Any neat one liner?
Well here's a one-liner with vanilla JS:
Object.keys(filter).forEach(v => filter[v] = false)
It does use an implicit loop with the .forEach() method, but you'd have to loop one way or another (unless you reset by replacing the whole object with a hardcoded default object literal).
Using lodash, mapValues is a graceful, loop-free way:
filter = {
"ID": false,
"Name": true,
"Role": false,
"Sector": true,
"Code": false
};
filter = _.mapValues(filter, () => false);
If you want to do this with Underscore.js, there is an equivalent, but with a slightly different name:
filter = _.mapObject(filter, () => false);
In either case, the value of filter will be set to:
{ ID: false,
Name: false,
Role: false,
Sector: false,
Code: false }
If you're not using ES6, here is its ES5 counterpart.
Object.keys(filter).forEach(function(key, value) {
return filter[key] = false;
})
If you don't want to modify the array, here's an ES6 alternative that returns a new one:
Object.fromEntries(Object.keys(filter).map((key) => [key, false]))
Explanation:
Object.keys returns the object's keys:
Object.keys({ a: 1, b: 2 }) // returns ["a", "b"]
Then we map the result ["a", "b"] to [key, false]:
["a", "b"].map((key) => [key, false]) // returns [['a', false], ['b', false]]
And finally we call Object.fromEntries that maps an array of arrays with the form [key, value] to an Object:
Object.fromEntries([['a', false], ['b', false]]) // returns { a: false, b: false }
A small line of code compatible with all browsers:
for(var i in your_object) your_object[i] = false;
With ES6 features one-liner without mutation:
{
...Object.keys(filter).reduce((reduced, key) => ({ ...reduced, [key]: false }), {})
}
hasOwnProperty must be used
```
for(var i in your_object) {
if (Object.hasOwnProperty.call(your_object, i)) {
your_object[i] = false;
}
}
```
In case you are dealing with 'scope' variables, this might be a better solution.
Object.keys(filter).reduce(function(accObj, parseObj) {
accObj[parseObj] = false;
return accObj;
}, {});
Here's what i would call a neat one-liner solution:
const filtered = Object.assign(...Object.keys(filter).map(k => ({ [k]: false })));
Demo:
const filter = {
'ID': false,
'Name': true,
'Role': false,
'Sector': true,
'Code': false
};
const filtered = Object.assign(...Object.keys(filter).map(k => ({ [k]: false })));
console.log(filtered);
We are basically converting the object into an array using Object.assign() so we can use the map() fucntion on it to set each propety value to false, then we convert the array back to an object using the Object.assign() with the spread operator :)

Categories

Resources