'How to remove a value that contains comma in array

dataSize.map((x) => {
 if(x.indexOf >-1 !== true) {
 return x;
}
});

the output is like this ['XL', undefined, 'S', undefined] instead of ['XL', 'S']



Solution 1:[1]

You can use array filters, if the function passed in as the parameter to the filter function returns falsey, it will be removed from the array.

Your solution, with map did not work because it manipulates values, but it doesn't remove them.

const dataSizes = ['XL', 'M,L,XL', 'S', 'X,L']
const filteredDataSizes = dataSizes.filter((size) => !size.includes(","));

console.log(filteredDataSizes);

Solution 2:[2]

You can use filter to iterate the array. And a good JS function to check this would include.

const dataSize = ['XL', 'M,L,XL', 'S', 'X,L']

let n = dataSize.filter(e => !e.includes(','))

console.log(n)

Solution 3:[3]

In terms of Array.map() and Array.filter(), the former is used for manipulating array elements and the latter for filtering, or in other words, selecting particular array elements based on a condition.

When using the includes() method, a case-sensitive search is performed to determine if a string can be found within another string, returning true or false as appropriate.

const dataSize = ["XL", "M,L,XL", "S", "X,L"];
console.log(dataSize.filter((s) => !s.includes(",")));

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Rida F'kih
Solution 2 Maik Lowrey
Solution 3