Covert comma-separated string to array - javascript

Trying to convert comma-separated string to array w/ quotes around each value in js:
var ipd = 'field1,field2';
console.log('Img Pad string: ' + ipd); // field1,field2
var ipdarray = new Array();
ipdarray = ipd.split(',');
console.log('Img Pad array split: ' + typeof ipdarray); // object
console.log('Img Pad array: ' + ipdarray); // field1,field2
I want the array to be: ["field1","field2"]
Tried to follow this: Convert comma separated string to array
but it's not converting to an array.

It is being converted to an array, but when you output the string (in console.log), the array is being coerced back into that string syntax because of the + operator (acting as a concatenator).
Here is a more isolated example of what is happening:
var string = 'field1,field2';
var arr = string.split(',');
console.log(Array.isArray(arr));
console.log(arr.length);
//When using the +, it will coerce into a string
console.log('Coerce to string ' + arr);
//When passing the array as an argument, it will stay an array
console.log('Stays and array', arr);
In order to preserve the array literal syntax, you'll need to JSON.stringify the array before outputting it if you want to use the + operator, or you can just output the array as a separate argument to console.log
JSON.stringify(ipdarray);
See it in action:
var ipd = 'field1,field2';
console.log('Img Pad string: ' + ipd); // field1,field2
var ipdarray = new Array();
ipdarray = ipd.split(',');
console.log('Img Pad array split: ' + typeof ipdarray); // object
console.log('Img Pad array: ' + JSON.stringify(ipdarray)); // ["field1","field2"]
// OR
console.log('Img Pad array: ', ipdarray); // ["field1","field2"]
Also, arrays are "object"s, but there are other ways to determine if that "object" is an instance of an array:
var arr = [];
console.log(typeof arr);
console.log(arr instanceof Array)
console.log(Array.isArray(arr));

Given input string you can use String.prototype.match() with RegExp /[^,]+/g to match one or more characters which are not comma ,
var ipd = 'field1,field2';
var ipdarray = ipd.match(/[^,]+/g);
Note that + operator converts array to string at
console.log('Img Pad array: ' + ipdarray); // field1,field2
use comma , operator at console.log() call
console.log('Img Pad array: ', ipdarray); // field1,field2

var a = "field1,field2"
var b = a.split(',');
var c = b.map(function (v) {
return '"' + v + '"';
})
console.log(c);
console.log(c[0]);
console.log(c[1]);

Related

Split multiple value in Array & create new array for split value in Java script

I want all index value that have data in array after ":" & split it to different Array at same index number. I am able to change data for one index value but its not changing for all value
var Array = ["Alice:", "John:654", "Bob:123"];
** After Split **
var Array = ["Alice:", "John:", "Bob:"];
var new array = ["", "654", "123"];
<script>
var array = ["Alice:", "John:654", "Bob:123"];
var el = array.find(a =>a.includes(":"));
let index = array.indexOf(el);
const newArray = el.split(':')[0] + ':';
var array2 = ["", "", ""];
array2[index] = newArray;
document.getElementById("demo").innerHTML = "The value of arry is: " + el;
document.getElementById("demo2").innerHTML = "The index of arry is: " + index;
document.getElementById("demo3").innerHTML = "split value: " + newArray;
document.getElementById("demo4").innerHTML = "new arr: " + array2;
</script>
If I understood your question correctly, this should be a solution:
const [oldOne, newOne] = array.reduce(
(acumm, current, index) => {
const [name, value] = current.split(':');
acumm[0].push(`${name}:`);
acumm[1].push(value ?? '');
return acumm;
},
[[], []]
);
Stackblitz Example
Info
// not mess up global vars, "Array" is a constructor
var Array = ["Alice:", "John:654", "Bob:123"];
** After Split **
var Array = ["Alice:", "John:", "Bob:"];
// not mess up with key words, "new" can only be called on
// constructors and array is as far i know not one
var new array = ["", "654", "123"];
Here's a solution using .map (so you don't need to keep track of the index)
var array = ["Alice:", "John:654", "Bob:123"];
var result = array.map(e => e.split(":")[1])
array = array.map(e => e.split(":")[0] + ":")
console.log(array, result)
Note that split(":")[1] will only give you the first entry if you have multiple ":" in the values, eg "John:654:999" - you can combine them with splice and join, eg:
parts.splice(1).join(":")
Here's the same solution, using a forEach if you prefer a single iteration over two:
var array = ["Alice:", "John:654:999", "Bob:123"];
var result = [];
var replacement = [];
array.forEach(e => {
var parts = e.split(":");
replacement.push(parts[0] + ":")
result.push(parts.splice(1).join(":"))
});
console.log(replacement, result)

Scan for duplicate values in a string and remove them

I am attempting to scan through and remove any duplicates from a string.
Here is an example scenario:
var str = "Z80.8, Z70.0, Z80.8";
The goal is to pass str into a function and have it returned as "Z80.8, Z70.0"
The string is separated by commas.
Use something like:
str
.split(',')
.map(function(s) { return s.trim() })
.filter(function(v, i, a) { return a.indexOf(v) === i })
.join(', ');
Split will make it an array by splitting the string at every comma.
Map will remove leading and trailing spaces.
Filter will remove any element that is already in the array.
Join will join back the array to one string.
Use regex to get each value and then use Set to remove duplicates.
const data = "Z80.8, Z70.0, Z80.8";
const res = [...new Set(data.match(/\w+\.[0-9]/g))];
console.log(res);
Javascript code splits the string on ", " then defines an anonymous function passed to filter, that takes three parameters representing the item, index and allitems. The anonymous function returns true if the index of this item is the same as the first index of that item found, otherwise false. Then join the elements of the Arrray on comma.
var str = "Z80.8, Z70.0, Z80.8";
var res = str.split(", ").filter(function(item,index,allItems){
return index == allItems.indexOf(item);
}).join(', ');
console.log(res);
Result:
Z80.8, Z70.0
Try this:
let str = "Z80.8, Z70.0, Z80.8";
str = [...new Set(str.split(", "))].join(", ");
console.log(str);
let str = "Z80.8, Z70.0, Z80.8";
let uniq = [...new Set(str.split(", "))].join(", ");
You can convert string to array using split() and then convert it to Set and then again join() it
var str = "Z80.8, Z70.0, Z80.8";
str = [... new Set(str.split(', '))].join(', ')
console.log(str);
I suggest to split this into an array then remove duplicates.
var arr = str.replace(" ", "").split(",");
var uniqueArray = arr.filter((v, i, arr) => arr.indexOf(v) === i);

Join Array items' strings which contain commas inside

Input Array:
["a,b,c", "foo,bar", "1,2,1", "a"] // should convert to → '"a,b,c","foo,bar","1,2,1","a"'
Now, using toString() or .join("") will produce the unwanted:
var arr = ["a,b,c", "foo,bar", "1,2,1", "a"];
console.log( arr.toString() )
console.log( arr.join(',') )
So, to bypass that, the first which comes to mind is JSON.stringify:
var arr = ["a,b,c", "foo,bar", "1,2,1", "a"];
var s = JSON.stringify(arr).slice(1,-1);
console.log( typeof s, ":" , s )
↑ The above is the wanted result, but i'm sure there's a cleaner way of doing it
Question:
Is this the only way to convert an Array which has string items containing commas to a String?
Here is another way to get the same result as with stringify (except when arr contains strings with embedded double-quotes):
arr.reduce((a, c, i) => a + (i > 0 ? ',"' : '"') + c + '"', '')
It depends on what "converting to string" means to you. An array is an ordered list of items numerically accessed. A string is a textual representation of that ordered list. If your question is "how to convert an array to a string while still being able to get the original array back," then the most performant answer would be JSON.stringify to convert the Array to a String, then JSON.parse to convert the string back into an array. However, JSON.stringify is only one of the many ways you could convert an array to a string.
A simple way to join all the strings in the array together is either by using Array.prototype.join.call or String.prototype.concat.apply
"use strict";
(function(){
var arr = ["a,b,c", "foo,bar", "1,2,1", "a"];
console.log( "Array.prototype.join: ", arr.join("") );
console.log( "String.prototype.concat: ", String.prototype.concat.apply("", arr) );
})();
Another way you could convert an array to a string is by going through each string in the array and concatenating them together.
"use strict";
(function(){
var arr = ["a,b,c", "foo,bar", "1,2,1", "a"];
var res = "";
var i = arr.length;
var curStr = "";
while (i--) {
curStr = arr[i];
// when the item on the left side is a string, the "+"
// operator acts as a concatination operator
res = res + curStr + ",";
// res += curStr + ","; // works just as well
// res += arr[i] + ","; // also works too
}
console.log( res );
})();
Using the fact that we can go through each item in the array, and look at each string individually, we can do something like converting each string to a base64 blob, then joining each string with a line break.
"use strict";
(function(window){
var btoa = window.btoa, atob = window.atob;
function encode(theArray){
var i = theArray.length, res = "";
while (i--) res += btoa(theArray[i]) + "\n";
return res.slice(0,-1);
}
function decode(theString){
var splitted = theString.split("\n");
var i = splitted.length, res = [];
while (i--) res.push( atob(splitted[i]) );
return res;
}
var arr = ["a,b,c", "foo,bar", "1,2,1", "a"];
var encoded_arr = encode(arr);
console.log("encoded_arr: ", JSON.stringify(encoded_arr, null, 1).replace(/\\n/g, "\n") );
var decoded_arr = decode(encoded_arr);
console.log( "decoded_arr", JSON.stringify(decoded_arr, null, 1).replace(/\\n/g, "\n") );
})(self);
There are countless more ways to join an array of strings together depending on your specific needs. Below are many such examples. Please emphasize that while all the following "work", none of them are as efficient as Array.prototype.join.
String.prototype.replace
function joinWithRegexp(str1, str2) {
return str1.replace(new RegExp("$"), str2);
}
console.log(joinWithRegexp("Foo", " bar"));
String.prototype.padStart
function joinWithPadStart(str1, str2) {
return str2.padStart(str1.length + str2.length, str1);
}
console.log(joinWithPadStart("Foo", " bar"));
String.prototype.padEnd
function joinWithPadEnd(str1, str2) {
return str1.padEnd(str1.length + str2.length, str2);
}
console.log(joinWithPadEnd("Foo", " bar"));
Template Literals
function joinWithTemplateLiteral(str1, str2) {
return `${str1}${str2}`;
}
console.log(joinWithTemplateLiteral("Foo", " bar"));
DOM
var tmpElement = document.createElement("div");
function joinWithDOM(str1, str2) {
tmpElement.appendChild(document.createTextNode(str1));
tmpElement.appendChild(document.createTextNode(str2));
return tmpElement.textContent;
}
console.log(joinWithDOM("Foo", " bar"));
Blob
var reader = new FileReader;
function joinWithBlob(str1, str2, thenFunc) {
reader.onload = function(){ thenFunc( reader.result ); };
reader.readAsText(new Blob([str1, str2]));
}
joinWithBlob("Foo", " bar", function(result){
console.log(result);
});

search on string with array with javascript

search on string with array with javascript
i have a string, i need to search on it with array.
for ex.
// that is array what i have
var arr = ['egypt', 'london', 'spain'];
// that is strings what i have
var str = "hello from egypt";
var str2 = "hello from london and spain";
ex. for first string, i need to now if it contain any values from array, and get it.
like : // found one value 'egypt' on str.
like : // found two values 'london, spain' on str2.
You can use includes to see if array elements exist in the string or not
Here's the code that resolves your problem
// that is array what i have
var arr = ['egypt', 'london', 'spain'];
// that is strings what i have
var str1 = "hello from egypt";
var str2 = "hello from london and spain";
function searchWords(str){
var res="";
for(var i=0;i<arr.length;i++){
if (str.includes(arr[i])){
res+= arr[i] +' '
}
}
console.log('found one value '+res )
}
searchWords(str1);
searchWords(str2);
// that is array what i have
var arr = ['egypt', 'london', 'spain'];
// that is strings what i have
var str = "hello from egypt";
var str2 = "hello from london and spain";
function search_in_string(_string, _array){
var out_arr=[];
for(var key in _array){
if(_string.indexOf(_array[key]) !=-1){
out_arr.push(_array[key]);
}
}
return out_arr;
}
console.log(search_in_string(str, arr));
console.log(search_in_string(str2, arr));

How to preserve quotes on values in array

I have to redo the functionality of JSON.stringify for a class and I am stuck...
If I am passed an array, I need to return the exact array as a string. However, when I return the array, it strips the quotations off of any values that are strings. For example:
var arr = [8, "hello"];
var addQuotes = function(arr){
return ('[' + arr + ']');
}
addQuotes(arr);
//"[8, hello]"
However, I need it to return:
"[8, "hello"]"
How do I preserve the quotation marks on array values?
I propose this code :
var arr = [8, "hello"];
var arrString = arr.map(x => typeof x === 'string' ? "\"" + x + "\"" : x);
result = "\"[" + arrString.join(", ") + "]\""
console.log(result); // ) "[8, "hello"]"

Categories