0

I need to remove the empty string from the array inside another array and I need to return the whole array without an empty string, can anyone help me with this, array is below

const testArr = [
 {
 code: 'size',
 name: 'Size',
 options: ['small', "", "", "large"],
 
 },
 {
 code: 'color',
 name: 'COlor',
 options: ['black', "", "", "red"],
 
 },
 ]

I need result like this(without empty string)

[
 {
 code: 'size',
 name: 'Size',
 options: ['small', "large"],
 },
 {
 code: 'color',
 name: 'COlor',
 options: ['black', "red"],
 },
]
asked Nov 4, 2020 at 11:51
2
  • use .filter() method to filter out the empty strings: array.filter(s => s.trim().length > 0) Commented Nov 4, 2020 at 11:53
  • but .filter() is returning only options, I need a whole array without empty string @Yousaf Commented Nov 4, 2020 at 11:54

1 Answer 1

1

Use .map() method to iterate over testArr and transform its elements and use .filter() method on the options array in each object, to filter out the empty strings.

const testArr = [
 { code: 'size', name: 'Size', options: ['small', "", "", "large"] },
 { code: 'color', name: 'COlor', options: ['black', "", "", "red"] }
];
const result = testArr.map(obj => {
 obj.options = obj.options.filter(s => s.trim().length > 0);
 return obj;
});
console.log(result);

answered Nov 4, 2020 at 12:00
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.