Array.join() with condition - javascript

How can I use Array.join() function with condition
For example:
var name = ['','aa','','','bb'];
var s = name.join(', ');
The output is: ', aa, , ,'bb',
I want to add a condition that will display only words that are not empty: "aa, bb"

You can use Array#filter to remove empty elements from array and then use Array#join on filtered array.
arr.filter(Boolean).join(', ');
Here, the callback function to filter is Boolean constructor. This is same as
// ES5 equivalent
arr.filter(function(el) {
return Boolean(el);
}).join(', ');
As empty strings are falsy in JavaScript, Boolean('') will return false and the element will be skipped from the array. And the filtered array of non-empty strings is joined by the glue.
var arr = ['', 'aa', '', '', 'bb'];
var s = arr.filter(Boolean).join(', ');
console.log(s);
You can also use String#trim to remove leading and trailing spaces from the string.
arr.filter(x => x.trim()).join(', ');

Related

How to ouput value of matching case in an array

I have an array
var hashtags = [ '#hr', '#acc', '#sales', '#hr' ];
I understand that to look for a specified matching value I'd have to use this
if (hashtags.indexOf("#hr") > -1)
// output value
But how do I output ALL the matching values that match the condition?
You can use Array#filter and equality comparison to get all the occurrences of your word in the given array.
var hashtags = [ '#hr', '#acc', '#sales', '#hr' ];
var result = hashtags.filter( word => word === '#hr');
console.log(result);
You can use Array#filter and check inside the condition. Also instead of indefOf you can use Array#includes function.
const hashtags = [ '#hr', '#acc', '#sales', '#hr' ];
const filteredHashtags = hashtags.filter(item => item.includes('#hr'));
console.log(filteredHashtags);
string [] arr = {"One","Two","Three"};
var target = "One";
var results = Array.FindAll(arr, s => s.Equals(target));

javascript array - separate values and values of values by single quotes

I have an array that looks like this:
var array = ["Rock Paper,Shoot,Dulce", "Once,Apple Mic,Chairs"]
I want to return the results like this:
'Rock Paper','Shoot','Dulce','Once','Apple Mic','Chairs'
This is what I have done so far:
includes = tagsI.map(tag => `'${tag}'`).join(',')
But this only separates by commas and single quotes the values.. not the values of the values as well.
How can I do this?
Thank you
Join the items of the array to a single string with commas. Split the string by the comma separators, map the items to the required format, and join again with commas.
const array = ["Rock Paper,Shoot,Dulce", "Once,Apple Mic,Chairs"]
const result = array
.join(',')
.split(',')
.map(tag => `'${tag}'`)
.join(',');
console.log(result);
split tag by comma and use another map
var tagsI = ["Rock Paper,Shoot,Dulce", "Once,Apple Mic,Chairs"]
var result = tagsI.map(tag => tag.split(',').map(tag => `'${tag}'`)).join(',');
console.log(result)
How about using reduce :
var array = ["Rock Paper,Shoot,Dulce", "Once,Apple Mic,Chairs"];
//V1 : compatible with all browsers
var result = array.reduce((acc, elem, index, arr)=>{
var n_arr = elem.split(",").map(map_elem=> `'${map_elem}'`);
n_arr.forEach(fe_elem => acc.push(fe_elem));
return acc;
}, []).join(",");
console.log(result);
document.querySelector("#res1").innerHTML = result;
//V2: compatible with some browsers
var result2 = array.reduce((acc, elem, index, arr)=>{
var n_arr = elem.split(",").map(map_elem=>`'${map_elem}'`);
acc.push(...n_arr);
return acc;
}, []).join(",");
console.log(result2)
document.querySelector("#res2").innerHTML = result2;
<body>
<p id="res1"></p>
<p id="res2"></p>
</body>
The principle is the following :
We have an initial Array "array" in which we stored strings (["Rock Paper,Shoot,Dulce", "Once,Apple Mic,Chairs"])
For each string in the array:
We split in an array the said string by ","
We surround each element of this array by quotes
We add each of these elements to the array that will be used as the result variable
We created a string joining by ","
PS: If you want an array instead of a string, just remove the join(",")
You'll first need to split each element in the array.
var array = ["Rock Paper,Shoot,Dulce", "Once,Apple Mic,Chairs"];
var split = array.map(v => v.split(","));
var flattened = [].concat.apply([], split);
var str = flattened.join(",");

Allowing commas to follow through when converting array to string

I have an array of character with commas separating them. I need to split an array but retain my comma inbetween each character.
See below for an example array:
var myArray = [a,,,b,c,d,,,]
There's a comma in there between the characters "a" and "b". I need to retain the comma when converting the array to a string.
The output string needs to resemble this:
a,bcd,
This is what i'm currently doing to retain the commas:
myArray.toString().replace(/,/g, "");
The Array's toString() method basically does a join(",") which is why you are getting the extra commas in your string.
Instead use join("") if you want to join the elements without the delimiter being added as part of the string
var myArray = ["a",",","b","c","d",",",]
document.body.innerText = myArray.join("");
How about you use :
var myArray = [a,,,b,c,d,,,];
var str = myArray.join();
This will give a string of array elements, preserving the commas.
if you want it to maintain the centre comma you should create your array as
var myArray = [a,",",b,c,d,",",];
this will then treat the middle comma in the set of 3 as a string containing that character rather than the array seperator
You could change your regex, to replace item,item for item item.
myArray.toString().replace(/([a-z,]),([a-z,])/g, "$1$2")
Basically you have a sparse array and want to extract only filled values and convert it to string ? Here is one, probably not the best, solution :
var myArray = ['a',',',',','b',',','c']
var resultArray = [];
for(var i = 0; i < myArray.length; i++){
if(myArray[i] !== ','){// allow 0, false, null values, but not undefined
resultArray.push(myArray[i]);
}
}
console.log(resultArray);
Working plnkr : http://plnkr.co/edit/55T6PGI9DuTlvy6k88hr?p=preview, check the console of your broswer.
If this is an actual array of strings and you wanted only those with actual values, you could use the filter() function to filter out any non-undefined ones :
// Your example array
var input = ['a',,,'b','c','d',,,];
// Remove any undefined elements
var output = input.filter(function(e){ return e; }); // yields ['a','b','c','d']
You could then use the join() function to create a string with your elements :
var result = output.join(); // yields "a,b,c,d"
Example Snippet
var input = ['a',,,'b','c','d',,,];
document.write('INPUT: ' + input + '<br />');
var output = input.filter(function(e){ return e; });
document.write('OUTPUT: ' + output);

What is the `filter` call for in this string split operation?

I have a line of legacy code to split a string on semi-colons:
var adds = emailString.split(/;+/).filter(Boolean);
What could the filter(Boolean) part do?
filter(Boolean) will only keep the truthy values in the array.
filter expects a callback function, by providing Boolean as reference, it'll be called as Boolean(e) for each element e in the array and the result of the operation will be returned to filter.
If the returned value is true the element e will be kept in array, otherwise it is not included in the array.
Example
var arr = [0, 'A', true, false, 'tushar', '', undefined, null, 'Say My Name'];
arr = arr.filter(Boolean);
console.log(arr); // ["A", true, "tushar", "Say My Name"]
In the code
var adds = emailString.split(/;+/).filter(Boolean);
My guess is that the string emailString contains values separated by ; where semicolon can appear multiple times.
> str = 'a#b.com;;;;c#d.com;;;;dd#dd.com;'
> str.split(/;+/)
< ["a#b.com", "c#d.com", "dd#dd.com", ""]
> str.split(/;+/).filter(Boolean)
< ["a#b.com", "c#d.com", "dd#dd.com"]
Here split on this will return ["a#b.com", "c#d.com", "dd#dd.com", ""].

javascript function takes string and returns array

First I have an array that has two strings in it.
var Array = ["firstName lastName" , "anotherString"]
I would like to create a function that takes in a string as a parameter and returns an array by breaking up the input string into individual words. So the output in this example would be ["firstName", "lastName"] ?
I know it would look something like this
var newFun = function(string) {
return string[0] // than do something else
}
Help is greatly appreciated!
So simple, use the String.prototype.split method to split strings into array list.
MDN:
The split() method splits a String object into an array of strings by separating the string into substrings.
return str.split(' ');
#Christoph:
You are using some very bad conventions here.
var Array
function (string)
Array is a predefined class in javascript and string is pretty close to the predefined class String, so just avoid using them completely.
var arr;
function (str)
Short Method: splits a string with multiple words, handles funky strings that String.prototype.split(' ') can't handle like " firstName Lastname" or just "firstName Lastname". returns an Array
function smartSplit (str) {
// .trim() remove spaces surround the word
// /\s+/ split multiple spaces not just one ' '
return str.trim().split(/\s+/);
}
Test Case:
// case: split(' ');
console.log(" firstName lastName".split(' '));
// result: ["", "", "", "firstName", "", "", "", "lastName"]
// case: split(/\s+/)
console.log(" firstName lastName".split(/\s+/));
// result: ["", "firstName", "lastName"]
// case: .trim().split(/\s+/)
console.log(smartSplit(" firstName lastName"));
// result: ["firstName", "lastName"]
Complete Method: same as smartSplit except for it expects an Array as a parameter instead of a String
function smartSplitAll (strArr) {
var newArr = [];
for (var i = 0; i < strArr.length; i++) {
// expecting string array
var str = strArr[i].trim();
// split the string if it has multiple words
if (str.indexOf(' ') > -1)
newArr = newArr.concat(str.split(/\s+/));
else
newArr.push(str);
}
return newArr;
}
console.log(smartSplitAll(["firstName lastName", "anotherString"]);
// result: ["firstName", "lastName", "anotherString"]
Code lives here: http://jsfiddle.net/8xgzkz16/
The index of [0] is actually the first character of the string.
Do this:
var myString = "My Name";
var splitResult = myString.split(" ");
Will result in:
["My", "Name"]
You could do something like this using the split method from the object String
var newFun = function(string) {
return string[0].split(" ");
}
VoilĂ  !
You can use the string split method:
function splitString(input) {
return input.split(" ");
}
Several comments on your code:
1) the function you are looking for is String.prototype.split:
var string = "firstName lastName";
string.split(" ");
// returns an array: ["firstName","lastName"]
2) don't call your array Array. This is a "reserved word"* for the Array prototype! You are overwriting the prototype, if you do so!
3) Keep the naming of your parameters consistent. This way you avoid error like you did in your code. Handing over an array and call the parameter string is a bad idea. string[0] returns the first symbol of the string, array[0] the first element of your array. Also, name the function appropriately.
Your code should look like this:
var array = ["firstName lastName" , "anotherString"];
function returnSplitString(string){
return string.split(" ");
}
var splitStringArray = returnSplitString(array[0]);
* In the strict technical sense it is not, because you CAN name your variable that way, however it's a bad idea to do so.
var newFun = function(str) {
return str.split(" ");
}
This splitter will take any array with mixed string (strings with spaces and without spaces) and split them in a linear array.
var splitter = (array) => {
return array.reduce((acc, value) => {
return /\s/.test(value) ? acc.concat(value.trim().split(' ')) : acc.concat(value) ;
}, []);
}
console.log(splitter(["There is proper space", "ThereIsNoSpace"]));
will output:
['There', 'is', 'proper', 'space', 'thereisnospace']

Categories