Is there a way to delete commas between arrays in Javascript? - javascript

I'm creating a quiz which prints a list of clubs based on the user's answers. When I run it, however, there's a comma between each array which I don't want.
I tried to delete the commas but they are necessary between each item for the code to work.
I have this list:
var clubs=[[" Fall Production"," Spring Musical", ""],["Student Government", ""],["Tricorn", ""],["FBLA", ""]...] //and it continues
and then this function to print them:
function eliminateClubs(){
for(h=0;h<=personChoices.length;h++){
if (personChoices[h]==1){
recClubs.push(clubs[h].join(', <br/>'));
}
}
}
When it prints it looks like:
Fall Production,
Spring Musical,
, Student Government,
, Tricorn,
, FBLA,
etc...
I don't know how to get rid of the commas that appear before each different array, but the ones after each item are fine.

function eliminateClubs(){
for(h=0;h<=personChoices.length;h++){
if (personChoices[h]==1){
if (clubs[h].indexOf(',') > -1)
{
clubs[h] = clubs[h].replace(',','');
}
recClubs.push(clubs[h].join(', <br/>'));
}
}
}

I would suggest doing the below:
var p=[1,0,1,0];
var clubs=[[" Fall Production"," Spring Musical", ""],["Student Government", ""],["Tricorn", ""],["FBLA", ""]];
console.log(clubs.filter((a, i) =>p[i]==1).flat().filter((a) =>a ).map(a=>a.trim()).join(',<br>'));

Try this:
const clubs = [
["Fall Production"," Spring Musical", ""],
["Student Government", ""],
["Tricorn", ""],
["FBLA", ""]
];
// filter empty values of arrays of strings
const filteredClubs = clubs.map(arr => arr.filter(a => a));
// convert filteredClubs in a one level array
const oneLevelArrayClubs = filteredClubs.reduce((acc, next) => acc.concat(next));
// join them with what you wanted
const clubsString = oneLevelArrayClubs.join(', <br/>');

You can simply Array.flatMap through the array and use Array.filter:
var clubs=[[" Fall Production"," Spring Musical", ""],["Student Government", ""],["Tricorn", ""],["FBLA", ""]]
let result = clubs.flatMap(x => x.filter(y => y))
console.log(result)
Then you can do another Array.map if you want to add a line break and trim etc. If your data is cleaner however you can skip that step so you should try if possible to correct those empty spaces in your data etc.
let result = clubs.flatMap(x => x.filter(y => y)).map(x => x.trim())
Note: Array.flat and Array.flatMap they both do not have support in IE so you would need a polyfill
You can avoid that with Array.map / Array.reduce like so:
var clubs=[[" Fall Production"," Spring Musical", ""],["Student Government", ""],["Tricorn", ""],["FBLA", ""]]
let result = clubs.map(x => x.filter(y => y)).reduce((r,c) => [...r,...c], [])
console.log(result)

Related

Correct approach to get JSON node length in JS?

I have this simple JSON file that supposed to be one array Paths with 3 arrays (Path1, Path2, Path3) of objects.
{
"Paths":
{
"Path1": [{"x":"4","y":"182"},{"x":"220","y":"186"}],
"Path2": [{"x":"4","y":"222"},{"x":"256","y":"217"}],
"Path3": [{"x":"6","y":"170"},{"x":"216","y":"183"}]
}
}
Considering an online example that I found I am doing this to get the length of Paths node:
// It's Phaser 3 (JS game framework)
// this.cache.json.get('data') -> returns me the JSON contents
var json = this.cache.json.get('data');
for (var pos in json.Paths) {
var len = parseInt(json.Paths[pos].length)+1;
console.log(len);
}
Although it works I would like to know if this is the correct approach because it seems to be too much code only to get a node length.
Thanks!
If you are wanting to get a count of all the points in all paths you could access them using Object.values() and then reduce()
const data ={
"Paths":
{
"Path1": [{"x":"4","y":"182"},{"x":"220","y":"186"}],
"Path2": [{"x":"4","y":"222"},{"x":"256","y":"217"}],
"Path3": [{"x":"6","y":"170"},{"x":"216","y":"183"}]
}
}
const numPoints = Object.values(data.Paths).reduce((a,c) => (a + c.length), 0)
console.log(numPoints)
Not sure if you are trying to print the length of each path or get total length of all paths, if you want to print the length of each path then you can use map
let lengths = Object.values(json.Paths).map(path => path.length + 1)
console.log(lengths)
which will output
[ 3, 3, 3 ]
or forEach like you did
Object.values(json.Paths).forEach(path => console.log(path.length + 1))
if you need the total you can use reduce
let nodeLength = Object.values(json.Paths).reduce((acc, path) => acc + path.length, 0)
which will give you 6
Edit: since in the comment you said you needed to know how many elements are in your object, you can use
Object.keys(json.Paths).length
to get that

convert multi arrays in to object array with properties

I have a txt file that I split by the tabs, then I map out each line to an array. I would like to make these arrays
[
"saddle (seat)",
"asiento"
],
[
"seat clamp",
"abrazadera de asiento"
],
Into something like this, using Eng and Spa as properties:
{ Eng: saddle (seat),
Spa: asiento,
Eng: seat clamp,
Spa: abrazadera de asiento
}
This is my current code
var fs = require('fs');
var output = fs.readFileSync('component names.txt', 'utf8')
.replace(/(\r)/gm, "")
.split('\n')
.map(line => line.split('\t'))
/* .reduce(() => {}, )
components = []
components[].push({
Eng: line[0],
Spa: line[1]
}) */
console.log('output:', JSON.stringify(output, null, 2));
To get an array of objects, you just need to map() over the lines after you've split() on a \n. Do another split in \t and return the object:
let str = "saddle (seat)\tasiento\nseat clamp\tabrazadera de asiento"
let trans = str.split('\n').map(line => {
let [Eng, Spa] = line.split('\t')
return {Eng, Spa}
})
console.log(trans)
// Get all Spa values:
console.log(trans.map(item => item.Spa))
// Get all Eng values:
console.log(trans.map(item => item.Eng))
Edit Based on Comment
You can's just print trans.spa because that could be many values. To get all the Spa values you need to use map to get them all with something like:
trans.map(item => item.Spa)
(added to the excerpt above)

convert array to array of array

I am getting data from a Firebase database and want to be able to pass it into a function to be used in a Google Map. The required/desired format is below. I can get the data from Firebase into an but want to reformat it somehow to put it into the correct format.
I have passed the array itself and then tried to push it into the locations array but that obviously doesn't work.
Here is a console.log(); of the array and the format.
Current Array:
var array = ["Stop1, 37.3329891813207, -122.039420719004", "Stop2, 37.3320091546085, -122.036849794357", "Stop3, 37.3310547072562, -122.034668026436", "Stop4, 37.3301791417375, -122.033242200136", "Stop5, 37.3307185698498, -122.030606204886"]
initMap(array)
Desired Format:
function initMap(passedArray) {
//..Convert array here?..
var locations = [
['Stop1', 37.3329891813207, -122.039420719004],
['Stop2', 37.3320091546085, -122.036849794357],
['Stop3', 37.3310547072562, -122.034668026436],
['Stop4', 37.3301791417375, -122.033242200136],
['Stop5', 37.3307185698498, -122.030606204886]
];
}
Thanks.
Split by separator ', ' and parse numbers.
var array = ["Stop1, 37.3329891813207, -122.039420719004", "Stop2, 37.3320091546085, -122.036849794357", "Stop3, 37.3310547072562, -122.034668026436", "Stop4, 37.3301791417375, -122.033242200136", "Stop5, 37.3307185698498, -122.030606204886"]
const initMap = array => array
.map(str => str.split(', ').map((x, i) => (i ? parseFloat(x) : x)))
console.log(initMap(array))

How to get result from json object with angular js?

I have a json file and want to count the rows by specific value and load to my page using angular js models.
The json is look like this:
[
{"id":"1","district":"AL"," name":"Lisa Lz","gender":"Female"},
{"id":"2","district":"AL"," name":"Arnord Bk","gender":"Male"},
{"id":"3","district":"NY"," name":"Rony Rogner","gender":"Male"}
]
The json file loaded by $http service.
How can I run such query on the json data:
select COUNT(`name`) as a from tbl_ben where ` gender` = 'Female' and `district` = 'LA';
any idea? 
 
You can't run SQL queries on JSON out-of-the-box, so let's work through it in JavaScript.
We have some data in an array, let's call it people:
let people = [
{"id":"1","district":"AL"," name":"Lisa Lz","gender":"Female"},
{"id":"2","district":"AL"," name":"Arnord Bk","gender":"Male"},
{"id":"3","district":"NY"," name":"Rony Rogner","gender":"Male"}
];
Now, let's filter it down based on their gender and district like in your query:
let filtered = people.filter(p => (p.district === "LA") && (p.gender === "Female"));
Now instead of using COUNT, we can just check the length property of our filtered array:
let count = filtered.length;
We can abstract this code away into a nice function which will do the work for us:
let getCount = (array, predicate) => {
return array.filter(predicate).length;
};
And we can then use this function like so:
let people = [
{"id":"1","district":"AL"," name":"Lisa Lz","gender":"Female"},
{"id":"2","district":"AL"," name":"Arnord Bk","gender":"Male"},
{"id":"3","district":"NY"," name":"Rony Rogner","gender":"Male"}
];
getCount(people, p => p.district === "NY" && p.gender === "Male"); // 1
Note that based on your example data, the count is 0 as you have nobody in the district "LA".

Group by in javascript or angularjs

I just want to do sum value column based on the Year and my data is below, but I don't know how to do this either using angular(in script) or javascript.
[
{"Year":2013,"Product":"A","Value":0},
{"Year":2013,"Product":"B","Value":20},
{"Year":2013,"Product":"A","Value":50},
{"Year":2014,"Product":"D","Value":55},
{"Year":2014,"Product":"M","Value":23},
{"Year":2015,"Product":"D","Value":73},
{"Year":2015,"Product":"A","Value":52},
{"Year":2016,"Product":"B","Value":65},
{"Year":2016,"Product":"A","Value":88}
]
I want to perform the sum on Value column and remove Product column as well.
Thanks
Edit As commenters have pointed out, this doesn't even require Lodash. Been using Lodash so much for current project I forgot reduce is built in. :-)
Also updated to put data in desired form [{"yyyy" : xxxx},...].
This code will accomplish this:
var data = [{"Year":2013,"Product":"A","Value":0},{"Year":2013,"Product":"B","Value":20},{"Year":2013,"Product":"A","Value":50},{"Year":2014,"Product":"D","Value":55},{"Year":2014,"Product":"M","Value":23},{"Year":2015,"Product":"D","Value":73},{"Year":2015,"Product":"A","Value":52},{"Year":2016,"Product":"B","Value":65},{"Year":2016,"Product":"A","Value":88}];
var sum = data.reduce(function(res, product){
if(!(product.Year in res)){
res[product.Year] = product.Value;
}else{
res[product.Year] += product.Value;
}
return res;
}, {});
result = [];
for(year in sum){
var tmp = {};
tmp[year] = sum[year];
result.push(tmp);
}
console.log(result);
RESULT:
[{"2013" : 70}, {"2014" : 78}, {"2015" : 125}, {"2016" : 153}]
ORIGINAL ANSWER
The easiest way I can think of to do this is with the Lodash Library. It gives you some nice functional programming abilities like reduce, which basically applies a function to each element of an array or collection one by one and accumulates the result.
In this case, if you use Lodash, you can accomplish this as follows:
var data = [{"Year":2013,"Product":"A","Value":0},{"Year":2013,"Product":"B","Value":20},{"Year":2013,"Product":"A","Value":50},{"Year":2014,"Product":"D","Value":55},{"Year":2014,"Product":"M","Value":23},{"Year":2015,"Product":"D","Value":73},{"Year":2015,"Product":"A","Value":52},{"Year":2016,"Product":"B","Value":65},{"Year":2016,"Product":"A","Value":88}];
result = _.reduce(data, function(res, product){
if(!(product.Year in res)){
res[product.Year] = product.Value;
}else{
res[product.Year] += product.Value;
}
return res;
}, {});
This yields:
{
"2013": 70,
"2014": 78,
"2015": 125,
"2016": 153
}
Basically, what we're telling Lodash is that we want to go through all the elements in data one by one, performing some operation on each of them. We're going to save the results of this operation in a variable called res. Initially, res is just an empty object because we haven't done anything. As Lodash looks at each element, it checks if that Product's year is in res. If it is, we just add the Value to that year in res. If it's not, we set that Year in res to the Value of the current product. This way we add up all the product values for each year.
If you want to try it out you can do it here:
Online Lodash Tester
Cheers!
You could do this using plain JavaScript. We use an object that will hold the results and the forEach array method. The object that would hold the results would have as keys the years and as values the sums of the corresponding values.
var data = [
{"Year":2013,"Product":"A","Value":0},
{"Year":2013,"Product":"B","Value":20},
{"Year":2013,"Product":"A","Value":50},
{"Year":2014,"Product":"D","Value":55},
{"Year":2014,"Product":"M","Value":23},
{"Year":2015,"Product":"D","Value":73},
{"Year":2015,"Product":"A","Value":52},
{"Year":2016,"Product":"B","Value":65},
{"Year":2016,"Product":"A","Value":88}
];
groupedData = {};
data.forEach(function(item){
var year = item.Year;
var value = item.Value;
if(groupedData.hasOwnProperty(year)){
groupedData[year]+=value;
}else{
groupedData[year]=value;
}
});
console.log(groupedData);

Categories

Resources