Combine array in JavaScript with underscore character - javascript

Var a = "837297,870895"
Var b = "37297,36664"
OutPut = "837297_37297,870895_36664
I tried multiple script but does not working

You can split and map the splitted array as such:
var a = "837297,870895"
var b = "37297,36664"
var output = a.split(',').map((e,i)=> e+"_"+b.split(',')[i])
console.log(output.toString())
For ES2015 or lower
var a = "837297,870895"
var b = "37297,36664"
var output = a.split(',').map(function(e,i){return e+"_"+b.split(',')[i]})
console.log(output.toString())

You can start by converting the two strings (lists) into arrays using .map() and .split() methods.
Then use .map() and .join() methods to produce the desired string (list):
const a = "837297,870895";
const b = "37297,36664";
const [c,d] = [a,b].map(e => e.split(','));
const output = c.map((e,i) => `${e}_${d[i]}`).join();
console.log( output );

Related

seperate comma seperated string values in string variable

I am trying to extract the string which is like
var str = "[\"/home/dev/servers\", \"e334ffssfds245fsdff2f\"]"
Desired ouput
a = "/home/dev/servers"
b = "e334ffssfds245fsdff2f"
Here you are:
const str = "[\"/home/dev/servers\", \"e334ffssfds245fsdff2f\"]";
const object = JSON.parse(str);
const a = object[0];
const b = object[1];
console.log(a);
console.log(b);
The following will work fine for you.
var str = "[\"/home/dev/servers\", \"e334ffssfds245fsdff2f\"]";
var foo = JSON.parse(str); //Parse the JSON into an object.
var a = foo[0];
var b = foo[1];
Using JSON.parse()
let [a, b] = JSON.parse("[\"/home/dev/servers\", \"e334ffssfds245fsdff2f\"]")
console.log(a)
console.log(b)

Remove Duplicate elements from Array - Javascript (No JQuery & ECMAScript)

Case: We have 'n' number of arrays stored in an array (Array of Arrays). Now that each child array in this parent array can have elements that may or may not be present in other child arrays. Output - I need to create an array which has the all the elements present in all the child arrays excluding the duplicates.
I do not want to concatenate all the arrays into a single array and use unique method to filter out. I need to create unique array then and there during iteration.
Ex:
var a[] = [1,2,3,4,5];
var b[] = [1,2,7,8];
var c[] = [1,2,3,4,5,6,7,8];
var d[] = [9,10,11,12];
var arr[] = [a,b,c,d]
Output must be [1,2,3,4,5,6,7,8,9,10,11,12]
P.S: I can concat the arrays and use jquery unique function to resolve this, but i need a solution in javascript alone. Thanks
You can use array#reduce to flatten your array and then use Set to get distinct values and use array#from to get back array from Set.
var a = [1,2,3,4,5];
var b = [1,2,7,8];
var c = [1,2,3,4,5,6,7,8];
var d = [9,10,11,12];
var arr = [a,b,c,d]
var result = Array.from(new Set(arr.reduce((r,a) => r.concat(a))));
console.log(result);
Try using .filter when adding each array to the final one, filtering out the duplicates:
a.filter(function(item) {
return !finalArray.contains(item));
});
Answer using Sets:
var a = [1,2,3,4,5];
var b = [1,2,7,8];
var c = [1,2,3,4,5,6,7,8];
var d = [9,10,11,12];
var concat = a.concat(b).concat(c).concat(d);
var union = new Set(concat);
//console.log(union);
ES6 Answer:
let a = new Set([1,2,3,4,5]);
let b = new Set([1,2,7,8]);
let c = new Set([1,2,3,4,5,6,7,8]);
let d = new Set([9,10,11,12]);
let arr = new Set([...a,...b,...c,...d]);
//Result in arr.
Whats going on???
From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set:
The Set object lets you store unique values of any type, whether
primitive values or object references.
So when we initialise Sets passing arrays to the constructor we basically ensure that there are no duplicate values.
Then in the last line, we concat all the Sets we initialised prior into a final set.
The ... notation converts the Set into an array, and when we pass the 4 arrays to the constructor of the Set they get concatenated and a Set of their unique values is created.
Here is a functional alternative written in ES5.
var flatten = function(list) {
return list.reduce(function(acc, next) {
return acc.concat(Array.isArray(next) ? flatten(next) : next);
}, []);
};
var unique = function(list) {
return list.filter(function(element, index) {
return list.indexOf(element) === index;
})
}
var a = [1,2,3,4,5];
var b = [1,2,7,8];
var c = [1,2,3,4,5,6,7,8];
var d = [9,10,11,12];
var arr = [a,b,c,d];
var result = unique(flatten(arr));
console.log(result);
If you support ES6, arrow function can make that code even shorter.
Here is a solution that uses a plain object for resolving duplicates, and only uses basic ES3 JavaScript. Runs in IE 5.5 and higher, and with O(n) time complexity.
function uniques(arr) {
var obj = {}, result = [];
for (var i = 0; i < arr.length; i++) {
obj[arr[i]] = true;
}
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) result.push(+prop);
}
return result;
}
// Example use
var a = [1,2,3,4,5],
b = [1,2,7,8],
c = [1,2,3,4,5,6,7,8],
d = [9,10,11,12];
var result = uniques(a.concat(b, c, d));
console.log('Result: ' + result);
As an object can only have a unique set of properties (no duplicates), the use of all array values as properties in an object will give you an object with a property for each unique value. This happens in the first loop. NB: the value given to those properties is not relevant; I have used true.
Then the result is just the conversion of those properties back to array values. This happens in the second loop.
var a = [1,2,3,4,5];
var b = [1,2,7,8];
var c = [1,2,3,4,5,6,7,8];
var d = [9,10,11,12];
var result = a.concat(b,c,d);
function remvDup(result){
var tmp = [];
for(var i = 0; i < result.length; i++){
if(tmp.indexOf(result[i]) == -1){
tmp.push(result[i]);
}
}
return tmp;
}
console.log(remvDup(result));
Becuase the OP mentioned that he cannot use 'Set' as it is not supported on the targeted browsers, I would recommand using the 'union' function from the lodash library.
See union's documentation here

Javascript string to special array

I have a string:
var string = "test,test2";
That I turn into an array:
var array = string.split(",");
Then I wrap that array into a larger array:
var paragraphs = [array];
Which outputs:
[['test','test2']]
But I need it to output:
[['test'],['test2']]
Any clue how I can do this?
Just map each item into an array containing that item:
var string = "test,test2";
var result = string.split(",").map(x => [x]);
// ^--------------
console.log(result);
let test_string = "test,test2";
let result = test_string.split(',').map(item => [item])
console.log(result)
You can get expected result using array Concatenation.
var string = "test,test2";
var array = string.split(",");
var finalArray=[[array[0]]].concat([[array[1]]])
console.log(JSON.stringify(finalArray));
What version of JavaScript are you targeting?
This might be a general answer:
var arr = "test,test2".split(",");
var i = arr.length;
while(i--)
arr[i] = [arr[i]];

Regex for creating an array from String

I have a string as follows
var str = "[series-3,series-5,series-6],[a3,a4,a5],[class a,class b]";
I want to get three arrays from above string as follows
var arr1 = ["series-3","series-5","series-6"];
var arr2 = ["a3","a4","a5"];
var arr3 = ["class a", "class b"];
What regex should I use to achieve this?
Can this be done without regex?
Use String#split() method
var str = "[series-3,series-5,series-6],[a3,a4,a5],[class a,class b]";
// split string based on comma followed by [
var temp = str.split(/,(?=\[)/);
// remove [ and ] from string usning slice
// then split using , to get the result array
var arr1 = temp[0].slice(1, -1).split(',');
var arr2 = temp[1].slice(1, -1).split(',');
var arr3 = temp[2].slice(1, -1).split(',');
console.log(arr1, arr2, arr3);
Or same method with some variation
var str = "[series-3,series-5,series-6],[a3,a4,a5],[class a,class b]";
// Remove [ at start and ] at end using slice
// and then split string based on `],[`
var temp = str.slice(1, -1).split('],[');
// then split using , to get the result array
var arr1 = temp[0].split(',');
var arr2 = temp[1].split(',');
var arr3 = temp[2].split(',');
console.log(arr1, arr2, arr3);
RegEx and String methods can be used. It's better to create an object and store individual arrays inside that object.
var str = "[series-3,series-5,series-6],[a3,a4,a5],[class a,class b]";
// Match anything that is inside the `[` and `]`
var stringsArr = str.match(/\[[^[\]]*\]/g);
// Result object
var result = {};
// Iterate over strings inside `[` and `]` and split by the `,`
stringsArr.forEach(function(str, i) {
result['array' + (i + 1)] = str.substr(1, str.length - 2).split(',');
});
console.log(result);
var str = "[series-3,series-5,series-6],[a3,a4,a5],[class a,class b]";
var stringsArr = str.match(/\[[^[\]]*\]/g);
var result = {};
stringsArr.forEach(function(str, i) {
result['array' + (i + 1)] = str.substr(1, str.length - 2).split(',');
});
console.log(result);
To create the global variables(Not recommended), just remove var result = {}; and replace result by window in the forEach.
I would prefer to do it like this
var str = "[series-3,series-5,series-6],[a3,a4,a5],[class a,class b]",
arrs = str.match(/[^[]+(?=])/g).map(s => s.split(","));
console.log(arrs);
Just for the fun of it, another way where we add the missing quotes and use JSON.parse to convert it to a multidimensional array.
var str = "[series-3,series-5,series-6],[a3,a4,a5],[class a,class b]";
var result = JSON.parse("[" + str.replace(/\[/g,'["').replace(/\]/g,'"]').replace(/([^\]]),/g,'$1","') + "]");
console.log(result[0]);
console.log(result[1]);
console.log(result[2]);

converting a multidimentional JSON array to JS variables

imagine you have the following JSON:
{"zero":{"0":"foo","1":"foo2"},"one":"fooa","two":"foob"}
What is the most efficient way to convert it to :
var zero = ['foo','foo2'];
var one = 'fooa';
var two = 'foob';
JSON.parse:
var json = '{"zero":{"0":"foo","1":"foo2"},"one":"fooa","two":"foob"}';
var pJson = JSON.parse(json);
var zero = [ pJson.zero[0], pJson.zero[1] ];
var one = pJson.one;
var two = pJson.two;

Categories