Remove Whitespace-only Array Elements - javascript

Since using array.splice modifies the array in-place, how can I remove all whitespace-only elements from an array without throwing an error? With PHP we have preg_grep but I am lost as to how and do this correctly in JS.
The following will not work because of above reason:
for (var i=0, l=src.length; i<l; i++) {
if (src[i].match(/^[\s\t]{2,}$/) !== null) src.splice(i, 1);
}
Error:
Uncaught TypeError: Cannot call method 'match' of undefined

A better way to "remove whitespace-only elements from an array".
var array = ['1', ' ', 'c'];
array = array.filter(function(str) {
return /\S/.test(str);
});
Explanation:
Array.prototype.filter returns a new array, containing only the elements for which the function returns true (or a truthy value).
/\S/ is a regex that matches a non-whitespace character. /\S/.test(str) returns whether str has a non-whitespace character.

Another filter based variation - reusable (function)
function removeWhiteSpaceFromArray(array){
return array.filter((item) => item != ' ');
}

const words = ['spray', 'limit', 'elite', 'exuberant', ' ', ''];
const result = words.filter(word => word.trim().length > 0);
console.log(result);

a="remove white spaces"
a.split(' ').join('').split('');
It returns an array of all characters in {a="remove white spaces"} with no 'space' character.
You can test the output separately for each method: split() and join().

You removed an item from the array which reduced the array's length. Your loop continued, skipped some indexes (those which were down-shifted into the removed index), and eventually attempted to access an index outside of the new range.
Try this instead:
var src = ["1"," ","2","3"];
var i = src.length;
while(i--) !/\S/.test(src[i]) && src.splice(i, 1);
console.log(src);

And for a new generation (namely ES2015):
['1', ' ', 'c'].filter(item => item.trim() !== '')
More on trim()

Just simply do this example
// this is you array
let array = ["foo","bar","",""]
// remove blanks in array
let array_new_value = array.join(" ").trim().split(' ');
// Print to know if really works
console.log(array_new_value);
I hope this helps you!!

Here's another approach.
var data = JSON.parse(arrayval.split(/\s/).join(''));

function clearSpace(arr){
for (var key in arr) {
if (arr[key] == "") {
arr.splice(key, 1)
clearSpace(arr)
}
}
}
var arr = ["","a","b","",""]
clearSpace(arr)
//I hope this helps you!!
//Vu Tien Luong - 3GTEL

Related

JS Array.splice return original Array and chain to it

I have a string with values like this a,b,c,d and want to remove a specific letter by index
So here is what I did str.split(',').splice(1,1).toString() and this is (obviously) not working since splice is returning the values removed not the original array
Is there any way to do the above in a one liner?
var str = "a,b,c,d";
console.log(str.split(',').splice(1,1).toString());
Thanks in advance.
You can use filter and add condition as index != 1.
var str = "a,b,c,d";
console.log(str.split(',').filter((x, i) => i != 1).toString());
Another strange solution. Destructure the array, remove the unwanted index, get an object and join the values of it.
var string = "a,b,c,d",
{ 1: _, ...temp } = string.split(',')
console.log(Object.values(temp).join(','));
The alternate way using regex replace
var str = "a,b,c,d";
console.log(str.replace(/,\w+/, ''))
Splice works in place, so oneliner is
const arr = "a,b,c,d".split(','); arr.splice(1,1); console.log(arr.toString());
If you want an string in a oneliner, you have to hardcode the index in a filter
console.log("a,b,c,d".split(',').filter((item, i) => i != 1).toString())
Or two slices (not performant at all)
const arr = "a,b,c,d".split(',')
console.log([...arr.slice(0,1),...arr.slice(2)].toString())

Create a function which takes in a word and spells it out, by consecutively adding letters until the full word is completed

Create a function which takes in a word and spells it out, by consecutively adding letters until the full word is completed.
This is my code for the solution. I am super new to JS. Could someone tell me the problem? Thank you.
function spelling(str) {
var str1 = [...str]
var n
str1.index[n] = str.slice(0, n+1)
return str1
}
Expected output:
Test.assertSimilar(spelling("bee"), ['b', 'be', 'bee'])
Test.assertSimilar(spelling("cake"), ['c', 'ca', 'cak', 'cake'
Actual output:
TypeError: Cannot set property 'undefined' of undefined at spelling at
Object.handleError at ContextifyScript.Script.runInThisContext at
Object.exports.runInThisContext
First of all, you never initialized n.
In addition, what is str1.index? It does not exist. If you want to access a cell in an array you should use: array[i].
Moreover, after you defined n, you need to update it for every char.
What I did was to fix all of what I mentioned above, and I created an empty array, and for each char of str I'm pushing to the array a slice of str and update n (++n means to use n after increment it by 1).
function spelling(str) {
var str1 = [];
let n = 0;
for (c in str)
str1.push(str.slice(0, ++n));
return str1;
}
console.log(spelling('bee'));
function spelling(str) {
return str.split('').map((el,i)=>str.slice(0,i+1));
}
Map can take a second parameter which is the index of the array that map is being called on.
You can use substring to achieve this.
The substring() method extracts the characters from a string, between
two specified indices, and returns the new sub string.
function spelling(str) {
let result = [];
for (let i = 1; i <= str.length; i++) {
result.push(str.substring(0, i));
}
return result;
}
console.log(spelling('bee'));
/**
* spelling("hello") // Returns ["h", "he", "hel", "hell", "hello"]
*/
function spelling(str) {
var arr = [];
var len = str.length;
while (len) {
arr.unshift(str.substring(0, len--));
}
return arr;
}

Converting HTML element into array and dealing with null

I am using javascript to read an HTML element that contains an array, but I suppose it is just a string version of an array. So I have converted this to a javscript array of integers, however I am having a problem when the the HTML array is empty.
HTML: (empty array)
<div id="activelist"> [] </div>
HTML: (array contains values)
<div id="activelist"> [4, 5] </div>
I am using let activeMachines = document.getElementById("activelist").innerHTML; in my script to grab the values from the page.
if I console.log(activeMachines); It will return [] when the array is empty.
if I console.log(activeMachines); It will return [3, 5] when the array contains values.
Now to process this into a javascript array of integers I use:
//trim off the quotes and brackets
activeMachines = activeMachines.slice(2, -2);
//split into different objects
activeMachines = activeMachines.split(', ');
console.log(activeMachines.length);
Now the part I can't figure out:
When the array is empty console.log(activeMachines.length); will return 1
When the array has a value in it console.log(activeMachines); will return 1
when the array has two values in it console.log(activeMachines); will return 2
Is there a way to get the array.length to be 0 when it is empty? Maybe .length is the wrong operator to use?
Thanks for any help!
You could use JSON.parse and return an array.
function getValue(id) {
return JSON.parse(document.getElementById(id).innerHTML);
}
var data = ['activelist0', 'activelist1'].map(getValue);
console.log(data[0].length);
console.log(data[0]);
console.log(data[1].length);
console.log(data[1]);
<div id="activelist0"> [] </div>
<div id="activelist1"> [4, 5] </div>
Using JSON.parse, we can parse the innerHTML and get the actual type that you want to evaluate. Ensure you wrap it around in a try catch or else you will run into an error as there is no validator for the content inside the div.
Here's a quick example:
var activeList = document.querySelectorAll('.active-list');
var debug = document.getElementById('debug');
activeList.forEach(function(elem, index) {
try {
var arr = JSON.parse(elem.textContent);
debug.innerHTML += (index + 1) + ' result length is: ' + arr.length + '<br/>';
} catch (error) {
debug.innerHTML += (index + 1) + ' error';
}
});
<div class="active-list">[4, 5]</div>
<div class="active-list">[1]</div>
<div class="active-list">[]</div>
<div class="active-list">this should invoke an error!</div>
<br/>
<div id="debug"></div>
One further option:
// declaring a named function, using Arrow syntax:
const parseArray = (el) => {
// retrieving the text content of the current element ('el'),
// removing any leading and trailing spaces using
// String.prototype.trim() and then replacing the '['
// and ']' characters using String.prototype.replace,
// along with a regular expression; replacing those
// characters with an empty string:
let values = el.textContent.trim().replace(/\[|]/g, ''),
// if the length of the modified String is zero then we
// return an empty Array; otherwise w split the the
// String using String.prototype.split(), to split
// the String into an Array:
result = values.length === 0 ? [] : values.split(',');
// logging the result:
console.log(result);
// returning the result to the calling context:
return result;
}
// using document.querySelectorAll() to retrieve all <li>
// elements on the page, and then calling NodeList.prototype.forEach()
// in order to call the named function (note the deliberate lack of
// parentheses on the function name):
document.querySelectorAll('li').forEach(parseArray);
const parseArray = (el) => {
let values = el.textContent.trim().replace(/\[|]/g, ''),
result = values.length === 0 ? [] : values.split(',');
console.log(result);
return result;
}
document.querySelectorAll('li').forEach(parseArray);
<ul>
<li>[]</li>
<li>["1","2","3"]</li>
<li>[a,b,,d,e]</li>
</ul>
JS Fiddle demo.
References:
Arrow functions.
document.querySelectorAll().
NodeList.prototype.forEach().
Regular Expressions.
String.prototype.split().
Mixing data model with representation is a bad practice. A better way is to separate the two. For example:
var myData = [1,2,3];
function renderData(data)
{
return data.join(", ");
}
Thus, you can manipulate myData and always get the right result regardless of how data is rendered.

An if loop omitting an array

I have an array of strings like thisvar arr = ['BUTTON','BADGE','CHECKBOX]'
Now I need a if condition to be written for the strings except those present in the array. How do I do that??
I'm a beginner and know nothing much about javascript. Thanks in advance for your help.
I tried var arr = ['BUTTON','BADGE','CHECKBOX];
if(!arr){
//code to be executed
}
However this always returns false.
You can use indexOf:
if(arr.indexOf(test_variable) === -1){
// element doesn't exist in array
}
I don't really understand your question but maybe array.some can solve your problem:
var someString = 'BADGE';
var arr = ['BUTTON','BADGE','CHECKBOX' ];
if (arr.some(str => str === someString)) {
console.log("Exist");
} else {
console.log("Doesn't exist");
}
This is how to do it:
var pippo = "pippo";
var arr = ['BUTTON','BADGE','CHECKBOX'];
if(arr.indexOf(pippo) > -1){
console.log("contained!");
}
else{
console.log("not contained!");
}
First of all the last element of your array/list is not properly written as a string i.e 'CHECKBOX. You missed a single quote in the end so it should be 'CHECKBOX'
var arr = ['BUTTON','BADGE','CHECKBOX];
↓
var arr = ['BUTTON','BADGE','CHECKBOX'];
Secondly coming to your actual query, according to your question it seems you want to run a piece of code if a string is not present in the array.
For this, you can use the array.indexOf() function which returns the position/index of the variable in the array passed as a parameter to it & if the variable is not present in the array, it returns a value of -1
More about this:- https://www.w3schools.com/jsref/jsref_indexof_array.asp
So the code for that would be:-
var arr = ['BUTTON','BADGE','CHECKBOX'];
var str = 'foo'; //string not present in the array i.e arr
if(arr.indexOf(str) === -1) {
//your code here
}
length will works for you if comes 0, return 0 when not element exists in the arrayset
var arr = ['BUTTON','BADGE','CHECKBOX'];
console.log(arr.length)

Removing an element from a javascript array causing issues

So I'm a little stuck as to why this isn't working. I'm trying to remove all of the empty strings in an array and it keeps giving me back an array that is just one empty string. Any ideas?
function splitNames(){
var names = document.getElementById("1").value.split("\n");
for(var i = 0; i<=names.length; i++){
if(names[i]==""){
names = names.splice(i, 1);
console.log(names);
}
}
console.log(names);
}
The string would look like this by the way.
Hi
Hello
(remove this one)
Bonjour
blah
(remove this one)
(remove this one)
blah
The array comes out to this ["Hi", "Hello","",...]
Perhaps the simplest way to do this is to use the filter function and search for truthy values. By default, empty strings are false.
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
var strings = ["zebras", "trees", "forests", "", "hi", "wizards", "", "", "lizards"];
strings = strings.filter((e) => e);
console.log(strings);
It's important to note that empty strings by default are false. However, strings that contain only whitespace characters are true. In that scenario, my example would not work and you would have to do this
strings.filter((e) => e.trim());
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
function splitNames(){
// var names = document.getElementById("1").value.split("\n");
var names = "Hi\nHello\n \nGoodBye".split("\n");
var filteredNames = names.filter(function(item){
return item.trim() !== "";
});//filter
return filteredNames;
}//splitNames()
console.log( splitNames() );
Create a new array and push what you need.
function splitNames(){
var names = document.getElementById("1").value.split("\n");
var newArr = [];
for(var i = 0; i<=names.length; i++){
if(names[i]){
newArr.push(names[i]);
}
}
return newArr.join('\n');
//console.log(names);
}
try it:
function splitNames(){
var names = document.getElementById("1").value.split("\n");
var newArr = names.filter(function(name){
return name!=="";
});
return newArr;
}

Categories

Resources