How to build a simple string from a multidimensional array? - javascript

Basically, I have a multidimensional array that I need to build into a simple string.
Quite an easy question, although it has been eating away at me for quite some time now since I can't seem to nail it.
Here is an example of how my array could look with just 3 questions within it:
[["question1","answer1","answer2","answer3","answer4"],["question2","answer1","answer2","answer3","answer4"],["question3","answer1","answer2","answer3","answer4"]]
For example, D.rows[0][0] would be "question1" and D.rows[2][3] would be "answer3", just to clarify.
Here is how it must be saved into a string as:
question1,answer1,answer2,answer3,answer4
question2,answer1,answer2,answer3,answer4
question3,answer1,answer2,answer3,answer4
Each element must have a comma between them, and each question must be separated by a line-break.
This is what I currently have that is not working:
var fullString;
for (i = 0; i < csvArray.length; ++i)
{
second = secondArray[i];
for (j = 0; j < second.length; ++j)
{
fullString += entry[j] + "'";
}
fullString += "\n";
}
Thanks in advance!

try this
var s,a=[["question1","answer1","answer2","answer3","answer4"],"question2","answer1","answer2","answer3","answer4"],["question3","answer1","answer2","answer3","answer4"]];
for(i=0; i < a.length; i++){
s=(s)?s+"\n\r"+a[i].join():a[i].join();
}
jsfiddle example
In your own example: since you are going straight to adding to fullString, it should have an empty string for value, otherwise you will end up with undefined in the beginning.
var fullString="";
this part second = secondArray[i]; should have been
var second = csvArray[i];
and in a same way this fullString += entry[j] + "'"; should have been
fullString += second[j] + ",";

one liner:
var result = [["question1","answer1","answer2","answer3","answer4"],["question2","answer1","answer2","answer3","answer4"],["question3","answer1","answer2","answer3","answer4"]].join('\r\n');

something like this:
var questionAnswerSet= { "question1" : [
{ "answer1" : "value",
"answer2" : "value",
"answer3" : value}
],
"question2" : [
{ "answer1" : "value",
"answer2" : "value",
"answer3" : value}
],
}
and access like this:
questionAnswerSet[0].answer2 // question one answer 2
questionAnswerSet[1].answer2 // question two answer 2

for (var i=0; i<yourArray.length; i++) { // iterate on the array
var obj = yourArray[i];
for (var key in obj) { // iterate on object properties
var value = obj[key];
console.log(value);
}
}

If you have an array as this...
var arr = [["question1","answer1","answer2","answer3","answer4"],["question2","answer1","answer2","answer3","answer4"],["question3","answer1","answer2","answer3","answer4"]];
then...
var strArr = arr.join(',');
var strLine = arr.join('\n'); // string with line breaks.
will do that for you.
if you want different strings for each question-answer block, then...
var strJoinArr = [], strJoinLines = '';
for(var i = 0; i < arr.length; i++){
strJoinArr.push(arr[i].join(','));
strJoinLines += arr[i].join(',')+ '\n'; // string with line break
}
then to access each section you can use indexes,
For example, strJoinArr[2] will return 'question3,answer1,answer2,answer3,answer4'
more on .join()
more on .push()

This might be your solution if you plan ot change separators or number of answers.
var array = [["question1","answer1","answer2","answer3","answer4"],["question2","answer1","answer2","answer3","answer4"],["question3","answer1","answer2","answer3","answer4"]],
string = "";
for (var i = 0; i <= array.length - 1; i++) {
string +=array[i].join(', ');
string += "\n";
}
Also, in the less readable but also effective way, for any object of this structure
string = array.join('\r\n');

Related

Joining numbers together with a string

I know that for an array join() can be used to produce what I am trying to accomplish here, but I am working with a string. What method would work with a string?
I want my output to look like "3 then 4 then 5 then 6 then 7", etc.
I've come close to getting what I am looking for but my current code adds an extra "then" at the end, which is not what I want:
let appendString = '';
let then = ' then ';
function countUp(start) {
for(var i = 0; i < 10; i++){
appendString += (start++) + then;
}
console.log(appendString);
}
I do not want solutions, I just would appreciate being pointed in the right direction.
I will try to not spoil the fun for you.
Think of it like this. If you have an array that has all your numbers, can you join them using .join ?
Now the question will be how to initialise an array with the numbers you want.
Try looking into array initialisations.
Does this answer your question ?
You are right that with an array you can use join. The thing is that you can turn a series of sequential numbers to an array easily:
function countUp(start, end, then) {
let arr = Array.from({length: end-start+1}, (_, i) => start + i);
return arr.join(then);
}
console.log(countUp(1, 10, ' then '));
what about this?
let appendString = '';
let then = ' then ';
function countUp(start) {
for(var i = 0; i < 10; i++){
appendString += (start++)
if(i<9){
appendString+=then
}
}
console.log(appendString);
}
or
let appendArray = [];
let then = ' then ';
function countUp(start) {
for(var i = 0; i < 10; i++){
appendArray.push(start++);
}
console.log(appendArray.join(then));
}

JS check if the value of object exists

So, I have following js setup:
var NAMES = [];
function INFO(id,first,middle,last){
var newMap = {};
newMap[id] = [first, middle, last];
return newMap ;
}
Then,
for (var j = 0; j < NUMBER.length; j++) { //let say it there are three values
var my_name = all_names[j]; // has "185, 185, 185"
if (NAMES[my_name] !== 185){ //Needs to check here
NAMES.push(INFO(my_name,"sean","sdfsd","sdfsfd"));
}else{
}
}
alert(JSON.stringify(NAMES , null, 4));
Here is a screenshot of the alert:
I hardcoded the number "185" for this example. I need to check if the id of 185 exists, then skip to else. I am not sure how to check it. I tried typeof, undefinedetc. but no luck.
(In other words, I should only have one "185").
Any help? Thanks!
If I understood correctly what you are trying to achieve, you have to iterate over NAMES and check every element. For example, you could do it using [].some javascript function:
if (!NAMES.some(function(v){return v[my_name]})) {
...
} else {
}
If you want to remove duplication you can just use NAMES as an object instead of array like this
var all_names = [185, 185, 181],
NAMES = {};
for (var j = 0; j < all_names.length; j++) { //let say it there are three values
var my_name = all_names[j]; // has "185, 185, 185"
NAMES[my_name] = ["sean","sdfsd","sdfsfd"];
}
alert(JSON.stringify(NAMES, null, 4));
First of all I would recommend making a JS Fiddle or CodePen out of this so people can see the code running.
I believe that the issue is that NAMES[my_name] is not doing what you think it is. NAMES is an Array so when you say NAMES[my_name] you are really asking for the ITEM in the array so you are getting the entire object that you create in the INFO function. What you really want is to see if the object has an attribute that matches the value (e.g. "185" from the my_names array).
This is not the prettiest code but it will show you how to do what you really want to do:
var NAMES = [];
function INFO(id,first,middle,last){
var newMap = {};
newMap[id] = [first, middle, last];
return newMap ;
}
all_names = ["185", "186", "185"]
for (var j = 0; j < all_names.length; j++) {
var my_name = all_names[j];
if (NAMES.length == 0) {
NAMES.push(INFO(my_name,"sean","sdfsd","sdfsfd"));
} else {
var match = false;
for (var x = 0; x < NAMES.length; x++) {
console.log(NAMES[x][my_name] + ' : ' + my_name);
if(NAMES[x][my_name]) {
match = true;
}
}
if (!match) {
NAMES.push(INFO(my_name,"sean","sdfsd","sdfsfd"));
}
}
}
alert(JSON.stringify(NAMES , null, 4));
Note the if that looks at NAMES[x][my_name] - this is asking if the item at array index 'x' has an attribute of 'my_name' (e.g. "185"). I believe this is really what you are trying to do. As its after midnight I assure you that there is more concise and pretty JS to do this but this should show you the basic issue you have to address.
Try this code using hasOwnProperty method :
for (var j = 0; j < NUMBER.length; j++) { //let say it there are three values
var my_name = all_names[j]; // has "185, 185, 185"
if (!NAMES[my_name].hasOwnProperty("185")){ //Needs to check here
NAMES.push(INFO(my_name,"sean","sdfsd","sdfsfd"));
}else{
}
}

Using search method from string

I'm trying to count the number of times certain words appear in the strings. Every time I run it I get a
uncaught TypeErro: undefined is not a function
I just actually need to count the number of times each "major" appears.
Below is my code:
for(var i = 0; i < sortedarray.length; i++)
{
if(sortedarray.search("Multimedia") === true)
{
multimedia += 1;
}
}
console.log(multimedia);
Here is my csv file which is stored in a 1d array.
"NAME","MAJOR","CLASS STANDING","ENROLLMENT STATUS"
"Smith, John A","Computer Science","Senior","E"
"Johnson, Brenda B","Computer Science","Senior","E"
"Green, Daisy L","Information Technology","Senior","E"
"Wilson, Don A","Information Technology","Junior","W"
"Brown, Jack J","Multimedia","Senior","E"
"Schultz, Doug A","Network Administration","Junior","E"
"Webber, Justin","Business Administration","Senior","E"
"Alexander, Debbie B","Multimedia","Senior","E"
"St. John, Susan G","Information Technology","Junior","D"
"Finklestein, Harold W","Multimedia","Freshman","E"
You need to search inside each string not the array. To only search inside the "Major" column, you can start your loop at index 1 and increment by 4 :
var multimedia = 0;
for(var i = 1; i < sortedarray.length; i += 4)
{
if(sortedarray[i].indexOf("Multimedia") > -1)
{
multimedia += 1;
}
}
console.log(multimedia);
What you're probably trying to do is:
for(var i = 0; i < sortedarray.length; i++)
{
if(sortedarray[i].indexOf("Multimedia") !== -1)
{
multimedia++;
}
}
console.log(multimedia);
I use indexOf since search is a bit of overkill if you're not using regexes.
Also, I replaced the += 1 with ++. It's practically the same.
Here's a more straightforward solution. First you count all the words using reduce, then you can access them with dot notation (or bracket notation if you have a string or dynamic value):
var words = ["NAME","MAJOR","CLASS STANDING","ENROLLMENT STATUS"...]
var count = function(xs) {
return xs.reduce(function(acc, x) {
// If a word already appeared, increment count by one
// otherwise initialize count to one
acc[x] = ++acc[x] || 1
return acc
},{}) // an object to accumulate the results
}
var counted = count(words)
// dot notation
counted.Multimedia //=> 3
// bracket notation
counted['Information Technology'] //=> 3
I don't know exactly that you need this or not. But I think its better to count each word occurrences in single loop like this:
var occurencesOfWords = {};
for(var i = 0; i < sortedarray.length; i++)
{
var noOfOccurences = (occurencesOfWords[sortedarray[i]]==undefined?
1 : ++occurencesOfWords[sortedarray[i]]);
occurencesOfWords[sortedarray[i]] = noOfOccurences;
}
console.log(JSON.stringify(occurencesOfWords));
So you'll get something like this in the end:
{"Multimedia":3,"XYZ":2}
.search is undefined and isn't a function on the array.
But exists on the current string you want to check ! Just select the current string in the array with sortedarray[i].
Fix your code like that:
for(var i = 0; i < sortedarray.length; i++)
{
if(sortedarray[i].search("Multimedia") === true)
{
multimedia += 1;
}
}
console.log(multimedia);

Check if any word in string is in an array

I have a gigantic list (800 items) and one really long string. I want to get the first item in the array that matches the part of the string and stored in a variable.
My code currently:
for (var i = 0; i<gigantic_genre_array.length; i++) {
var test_genre = thelongstr.indexOf(gigantic_genre_array[i]);
if(test_genre != -1) {
tag1 = gigantic_genre_array[test_genre];
alert(tag1);
}
}
This doesn't work like I thought it would, any suggestions?
Try this:
for(var i = 0; i<gigantic_genre_array.length; i++){
var test_genre = thelongstr.indexOf(gigantic_genre_array[i]);
if(test_genre!=-1){
tag1 = gigantic_genre_array[i];
alert(tag1);
}
}
Do the process reversely it will be efficient too.
var wordArray = thelongstr.split(' ');
for(var i=0,len = wordArray.length; i < len; i++)
{
if(gigantic_genre_array.indexOf(wordArray[i]) > -1)
{
alert(wordArray[i]);
}
}
You may create a RegExp based on the array and test it against the string:
var gigantic_genre_array=['foo','bar','foobar'];
var thelongstr='where is the next bar';
alert(new RegExp(gigantic_genre_array.join('|')).exec(thelongstr)||[null][0]);
//returns bar

json sibling data

(forgive me if I use slightly incorrect language - feel free to constructively correct as needed)
There are a couple posts about getting data from JSON data of siblings in the returned object, but I'm having trouble applying that information to my situation:
I have a bunch of objects that are getting returned as JSON from a REST call and for each object with a node of a certain key:value I need to extract the numeric value of a sibling node of a specific key. For example:
For the following list of objects, I need to add up the numbers in "file_size" for each object with matching "desc" and return that to matching input values on the page.
{"ResultSet":{
Result":[
{
"file_size":"722694",
"desc":"description1",
"format":"GIF"
},
{
"file_size":"19754932",
"desc":"description1",
"format":"JPEG"
},
{
"file_size":"778174",
"desc":"description2",
"format":"GIF"
},
{
"file_size":"244569996",
"desc":"description1",
"format":"PNG"
},
{
"file_size":"466918",
"desc":"description2",
"format":"TIFF"
}
]
}}
You can use the following function:
function findSum(description, array) {
var i = 0;
var sum = 0;
for(i = 0; i < array.length; i++) {
if(array[i]["desc"] == description && array[i].hasOwnProperty("file_size")) {
sum += parseInt(array[i]["file_size"], 10);
}
}
alert(sum);
}
And call it like this:
findSum("description1", ResultSet.Result);
To display an alert with the summation of all "description1" file sizes.
A working JSFiddle is here: http://jsfiddle.net/Q9n2U/.
In response to your updates and comments, here is some new code that creates some divs with the summations for all descriptions. I took out the hasOwnProperty code because you changed your data set, but note that if you have objects in the data array without the file_size property, you must use hasOwnProperty to check for it. You should be able to adjust this for your jQuery .each fairly easily.
var data = {};
var array = ResultSet.Result;
var i = 0;
var currentDesc, currentSize;
var sizeDiv;
var sumItem;
//Sum the sizes for each description
for(i = 0; i < array.length; i++) {
currentDesc = array[i]["desc"];
currentSize = parseInt(array[i]["file_size"], 10);
data[currentDesc] =
typeof data[currentDesc] === "undefined"
? currentSize
: data[currentDesc] + currentSize;
}
//Print the summations to divs on the page
for(sumItem in data) {
if(data.hasOwnProperty(sumItem)) {
sizeDiv = document.createElement("div");
sizeDiv.innerHTML = sumItem + ": " + data[sumItem].toString();
document.body.appendChild(sizeDiv);
}
}
A working JSFiddle is here: http://jsfiddle.net/DxCLu/.
That's an array embedded in an object, so
data.ResultSet.Result[2].file_size
would give you 778174
var sum = {}, result = ResultSet.Result
// Initialize Sum Storage
for(var i = 0; i < result.length; i++) {
sum[result[i].desc] = 0;
}
// Sum the matching file size
for(var i = 0; i < result.length; i++) {
sum[result[i].desc] += parseInt(result[i]["file_size"]
}
After executing above code, you will have a JSON named sum like this
sum = {
"description1": 20477629,
"description2": 1246092
};
An iterate like below should do the job,
var result = data.ResultSet.Result;
var stat = {};
for (var i = 0; i < result.length; i++) {
if (stat.hasOwnProperty(result[i].cat_desc)) {
if (result[i].hasOwnProperty('file_size')) {
stat[result[i].cat_desc] += parseInt(result[i].file_size, 10);
}
} else {
stat[result[i].cat_desc] = parseInt(result[i].file_size, 10);
}
}
DEMO: http://jsfiddle.net/HtrLu/1/

Categories