convert multi arrays in to object array with properties - javascript

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)

Related

How to store data retrieved from the server into an array with JavaScript?

Can someone tell me how can I store the values of the CSV file into an array that I am retrieving from the web server.
Data example:
Time2,Price,Size
0.0,20998.0,69
0.0,20999.0,18042
0.0,21001.0,14783
0.0,21003.0,100
Suppose I have the following scenario shown below:
var url1 = 'path for CSV file'
$.get(url1, function(data) {
// data param contains all the data that I retrieved from the csv
});
using the above example, how can I store my data into an array so the end result looks like the following:
A very straight forward approach:
Split into lines on \n
Split each line ,
const csv = `Time2,Price,Size
0.0,20998.0,69
0.0,20999.0,18042
0.0,21001.0,14783
0.0,21003.0,100`;
const result = csv.split("\n").map(l=>l.split(','));
console.log(result);
Use a reducer (Array.reduce):
// create an array of arrays
const csvLines = `Time2,Price,Size
0.0,20998.0,69
0.0,20999.0,18042
0.0,21001.0,14783
0.0,21003.0,100`
.split("\n")
.map(v => v.split(","));
// bonus: to array of objects
let headers = csvLines.shift();
const fromCsv = csvLines.reduce( (acc, val) => [...acc, {
[headers[0]]: parseFloat(val[0]),
[headers[1]]: parseFloat(val[1]),
[headers[2]]: parseFloat(val[2]) } ], []);
console.log(fromCsv);

Extract unique values of a key in a object - Javascript/d3 legend

Consider the following simplified csv file
x,y,names
1,2,group1
3,2,group2
4,3,group1
7,8,group3
3,5,group2
which I am reading in with d3.csv and afterwards apply a some function on it
d3.csv('file_name.csv').then(data => {
render(dataset)
});
Could someone explain to me how I could extract the unique strings in the category names and store them in a list
---> iam_a_list = [group1, group2, group3]
The elements in this list will later be used as text for a legend in a plot.
You can use a set to get unique results. Just loop over your data and make an array of all the names. Then make a set, which will remove all the duplicates and give you a unique list.
Using .map() and d3.set().values()
let uniqueListOfNames= []
d3.csv('file_name.csv').then(data => {
// listOfNames = ['group1', 'group2', 'group1', 'group3', 'group2']
const listOfNames = data.map(row => row.names)
// uniqueListOfNames = ['group1', 'group2', 'group3']
uniqueListOfNames = d3.set(listOfNames).values()
});
Using a loop.
let uniqueListOfNames= []
d3.csv('file_name.csv').then(data => {
const listOfNames= []
for (const row of data) {
listOfNames.push(row.names)
}
// listOfNames= ['group1', 'group2', 'group1', 'group3', 'group2']
// uniqueListOfNames = ['group1', 'group2', 'group3']
uniqueListOfNames = d3.set(listOfNames).values()
});

How can I add superscripts and subscript in a string?

I have an array of objects containing lots of data or objects which I import and display in a webpage.
const arr = [
{
question: "What is molecular formula for water?",
options: ["H2O","CO2","H2O","H2O"]
}
]
So Is it possible to write superscript and subscript in a string? To make the numbers superscipted or subscripted while displaying in a webpage.
Note: I have array of around 1000 objects from which only 100 of them are displayed. Some of them may contain superscript whereas some of them may not. Isn't there any simpler way like using alt codes for super scripts and subscripts so that I can directly put it in string.
You could map your array of options to a formatted version of that option by using .replace() to wrap each number in <sup></sup> tags to make it appear as subscript text like so:
const arr = [
{
question: "What is molecular formula for water?",
options: ["H2O","CO2","H2O","H2O"]
}
]
const formatted = arr[0].options.map(elem => elem.replace(/(\d)/g, `<sub>$1</sub>`));
console.log(formatted);
document.body.innerHTML = formatted;
Regex free approach. Supports hydrated salts (like blue vitorl) and balancing numbers. To add hydrated salts, just add a dot
const arr = [{
question: "What is molecular formula for water?",
options: ["H2O", "CO2", "H2O", "H2O"]
},
{
question: "What is the molecular formula for Copper(II) sulphate?",
options: ["H2O", "(CuSO4).5H2O", "H2O2", "D2O"]
}
]
arr.forEach(obj => { // map the first array
let answer = obj["options"].map((options) => { // map all the answers
let op = options.split('').map((data, i) => { // split all the answer strings
if (!isNaN(data)) { // if the data is a number the add <sub> tags to it
if (options.split('')[i - 1] != "." && i != 0) { // if i = 0 is a number then it is a blancing number. Then don't add <sub> tags to it
// also check if the previous string is a dot. Means that has water of crystillization or any other extension
let str = "<sub>" + data + "</sub>"
return str
}else{
return data
}
} else {
return data // else return the string
}
})
return op.join("") // join the string
})
// logic to add data display it
let question = document.createElement("h1") // question
question.innerHTML = obj["question"] // append question content
document.body.appendChild(question) // append the question element to body
let ul = document.createElement("ul") // create unsorted list
answer.forEach((things) => { // for each of the answers
let ali = document.createElement("li") // create a li
ali.innerHTML = things // add answers to the lu
ul.appendChild(ali) // append the li to the ul
})
document.body.appendChild(ul) // append the ul to the body
})
We are just splitting your answers and checking if the data is a number. If it is then we add <sub> tags to it.
To display them, we create elements dynamically and in a loop, we add compounds to a li and then append that to a ul
Make sure to follow the basic chem rules while formatting compounds
Generic example for replacing digits in all values with unicode subscript digits :
var json = JSON.stringify( [ { question: "What is molecular formula for water?", options: ["H2O","CO2","H2O","H2O"] } ] )
var arr = JSON.parse(json, (k, v) => v.trim ? v.replace(/\d/, m => '₀₁₂₃₄₅₆₇₈₉'[m]) : v)
console.log(arr)
document.body.textContent = arr[0].options

Is there a way to delete commas between arrays in 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)

Writing a query parser in javascript

I'm trying to write a parser that supports the following type of query clauses
from: A person
at: a specific company
location: The person's location
So a sample query would be like -
from:Alpha at:Procter And Gamble location:US
How do i write this generic parser in javascript. Also, I was considering including AND operators inside queries like
from:Alpha AND at:Procter And Gamble AND location:US
However, this would conflict with the criteria value in any of the fields (Procter And Gamble)
Use a character like ";" instead of AND and then call theses functions:
var query = 'from:Alpha;at:Procter And Gamble;location:US';
var result = query.split(';').map(v => v.split(':'));
console.log(result);
And then you'll have an array of pairs, which array[0] = prop name and array[1] = prop value
var query = 'from:Alpha;at:Procter And Gamble;location:US';
var result = query.split(';').map(v => v.split(':'));
console.log(result);
Asuming your query will always look like this from: at: location:
You can do this:
const regex = /from:\s*(.*?)\s*at:\s*(.*?)\s*location:\s*(.*)\s*/
const queryToObj = query => {
const [,from,at,location] = regex.exec(query)
return {from,at,location}
}
console.log(queryToObj("from:Alpha at Betaat: Procter And Gamble location: US"))
However, adding a terminator allow you to mix order and lowering some keywords:
const regex = /(\w+):\s*(.*?)\s*;/g
const queryToObj = query => {
const obj = {}
let temp
while(temp = regex.exec(query)){
let [,key,value] = temp
obj[key] = value
}
return obj
}
console.log(queryToObj("from:Alpha at Beta;at:Procter And Gamble;location:US;"))
console.log(queryToObj("at:Procter And Gamble;location:US;from:Alpha at Beta;"))
console.log(queryToObj("from:Alpha at Beta;"))

Categories

Resources