Home > Mobile >  remove if data in array falsy in javascript
remove if data in array falsy in javascript

Time:06-23

falsy javscript

const value = ''
const example = [5,!!value&&value]

expectation result is [5]
reality result is [5,false]

is there any other way to check falsy in javascript ? I want to set the value is the value is valid

CodePudding user response:

You can have several approaches.

  1. Post-filter your array

    [5, value].filter((v) => v)

  2. Use spread opperator

    [5, ...value ? [value] : []]

  3. Add conditionally

    const example = [5]; value && example.push(value);

CodePudding user response:

const value = '';
const example = [5, value].filter((x) => !!x);
console.log(example)

You can use the array function filter to return an array with only the truthy values. This will give you [5].

Alternatively, if you are using es6, you can use the spread syntax to get the same result:

const value = '';
const example = [5, ...(value ? [value] : [])];
console.log(example)

Here we are spreading the result of a ternary. If the value is truthy, we give an array with the value inside it, otherwise we give an empty array.

Note, you may need babel to use es6 syntax depending on your target browsers etc.

CodePudding user response:

Use the every() method to iterate over the array, convert each value to boolean, negate it, and return the result. If all values in the array are falsy, the every method will return true.

function CheckIfHasFalsy(arr) {
  return arr.every(element => !element);
}

console.log(CheckIfHasFalsy([5, '', false])); // true
console.log(CheckIfHasFalsy([5, 'test', true])); // false

And This one remove falsy value from array:

myArray = [1, '', true]
var myFilterArray = myArray.filter(Boolean);

CodePudding user response:

you can use spread operator like this for example

const value = "test"
[5, ...value]
  • Related