I have an array that is generated based on user clicks from various questions and alerts like this:
Team A, Player 1, Yellow, C1
This kind of array is created every time an event happens (in a football match). After the match is complete I want to take each of these events and put them into my database. I would like to know how I can separate each part of the array with a ; so that the array that will be exploded will look something like this:
Team A, Player 1, Yellow, C1; Team B, Player 5, Red, S6
I have no problem creating the first array and just need to know how to add in the ; I am wondering if this perhaps becomes an array within an array?
Thank-you in advance
Maybe the following solves your problem (as long as I understand it correctly):
var array = ["Team A", "Player 1", "Yellow", "C1",
"Team B", "Player 5", "Red", "S6"];
var result = "";
for ( var i = 0; i < array.length; i += 4) {
result += array.slice(i, i+4).join(",");
if ( i+4 < array.length ) result += ";";
}
console.log(result);
// prints: Team A,Player 1,Yellow,C1;Team B,Player 5,Red,S6;
Later you can reverse this operation using split:
var array2 = result.split(/,|;/);
// array == array2
Assuming I understand your issue:
I think a 2 dimensional array would be the easiest way to achieve what you are after. You could also look at creating objects and placing those objects into an array. It appears as though you are doing this but I am not entirely sure as your example is not very informative.
It would be helpful to see your code to know how the array is being created, but your last statement is probably on the right track. It sounds like you need either an associative array, or better yet, a collection of some sort. What does this data represent?
Player 1 from Team A received a Yellow card? What is C1? If you can post some code and explain what it is that you're trying to capture it would be more helpful.
From your question I guess that you are using strings, not actual arrays.
Consider using array of objects, because event is a single entity, not a list of entities:
[{team:"Team A", player:"Player 1", type:"Yellow", code:"C1"},
{team:"Team B", player:"Player 5", type:"Red", code:"S6"}]
Code to add an event to array of objects:
function addEvent(events, team, player, type, code) {
events.push({team:team, player:player, type:type, code:code});
}
If you are required to store individual events as arrays:
[["Team A", "Player 1", "Yellow", "C1"],
["Team B", "Player 5","Red", "S6"]]
You can use this code to add an event to 'array of arrays':
function addEvent(events, team, player, type, code) {
events.push([team, player, type, code]);
}
You should ideally push these strings into an array and then push them to an array that includes all the other arrays (2 dimensional array) :
Example: http://jsbin.com/ecoput/2/edit
var data = [["Team A","Player 1","Yellow","C1"],["Team B","Player 5","Red","S6"]]
After this, you should join the array.
data.join(";");
This will result in:
"Team A,Player 1,Yellow,C1;Team B,Player 5,Red,S6"
Related
For the past few days i've been looking into Javascript and how to make list out of comparison, i found something about arrays, and while i knew that this is what i need, I couldn't understand how it exactly worked with my very little knowledge about Javascript.
I want to make a list, say we have 5 items (let's take a, b, c, d, e as examples) and you're asked to compare one to another (do u like "a" or "d"?) and each time you choose an item it gets a point and it keeps asking you until all the comparisons are made with each item, then a list is made out of those comparisons and the items with the most points are ranked first.
if there is an article, a video, a code that i can analyze, anything would help.
Thanks in advance
Here is an idea of how you could approach it.
So you could have the following setup:
const items = ["a", "b", "c", "d", ...and so on]
const pointsRecord = {"a": 0, "b": 0, "c": 0, ...and so on}
With these two pieces you can build pairs to compare, and keep track of the points of each item.
From your description it sounds like you want to compare every item with every other item on the list. You will probably have to loop through the list twice and build a comparison pair that you can output, or render on the screen.
You could write a function to build comparison pairs to look something like this:
const comparisonPairs = [
[ "a", "b" ],
[ "a", "c" ],
[ "a", "d" ],
[ "b", "c" ],
...and so on
]
With something like this you could iterate through comparisonPairs, render the pair on the screen or output to the terminal. Then take the input, and update the pointsRecord object. Something like:
pointsRecord = {
...pointsRecord, // copy over all the data from the original point record
[selectedItem]: pointsRecord[selectedItem] + 1 // increment the points of the selected item
}
After updating pointsRecord you could move on to the next pair.
To sort them at the end you would just have to run a sort function on the items. Something like:
const sortedItems = items.slice().sort((a, b) => pointsRecord[b] - pointsRecord[a]);
Adding the .slice() creates a new array so you don't alter the original typically this is good practice but you may want to sort the original in place depending on your use case.
This is just one approach. For sure you want to think about how you want to organize the data, which it sounds like you are already doing so you are on the right track. As you are working through this if you find that it's getting messy, updating things, and keeping track of the data, that may be a good sign to re-asses and re-think if there is a better way to store the information.
So I have a use case in which I enter indexes and descriptions which belong to a round. I created a JS function that allows me to enter these indexes and descriptions. When I strip the data from the post request I get the following data:
['0,This is a testround', '1,This is a new testround']
I want to split this data so that I can seperate the 0 in an index variable and the following description "This is a testround" in a description variable. Please note that the description can only contain comma's. The indexes are not always corresponding with the indexes of an array: [[0,"Description1"],[5,"Description2"]] could happen
A possible solution could be to split the string on a comma and use str[0] for the index and the other parts for the description but to me this would look like an ugly solution.
What should I do?
I use the following JS to save the rounds to a playerdata div from which i extract the list above (in which items is the list with the index and description)
function item_checkbox(items,n) {
return `
<input type="checkbox" style="display:none;" name="${itemList[n]}" value="${items}" checked>
`
}
function add_to_itemData(items, n) {
itemDataEl = document.getElementById(itemData[n])
itemDataEl.innerHTML = itemDataEl.innerHTML + item_checkbox(items, n)
}
Thanks for any help in advance
While you say that it would be an "ugly" solution to solve it by splitting, I think it's a pretty straightforward routine, given the format the data is returned to you.
['0,This is a testround', '1,This is a new testround'].map(v => v.split(','));
... would translate correctly to:
[
[ "0", "This is a testround" ],
[ "1", "This is a new testround" ]
]
But I guess I get what you mean. There are a few possible problems - for example, that of key uniqueness. You could solve this one by keeping each row into Javascript objects instead of arrays, and you can convert it quite easily by using Object.fromEntries(), since it conveniently accepts each row of bidimensional arrays as key/value pairs:
Object.fromEntries([
[ "0", "This is a testround" ],
[ "1", "This is a new testround" ],
[ "1", "This is a dupe testround" ] // this will overwrite the previous entry
]);
// {0: "This is a testround", 1: "This is a dupe testround"}
You might want to take a few extra steps for additional control, like using .trim() to remove leading or trailing whitespaces or testing/filtering/splitting them using a custom regex.
I have a scenario, where I have two different Objects.
Scenario to achieve:
From two objects I need to match the values which has "A1","B2", etc...
Since both the objects values are not in proper order, the loop is breaking and missing some values.
In my demo the object1 has same repeated value i.e. "C3", It should be displayed only once.
Final output required is I need to detect only the matched values from two objects and display its corresponding "a" and "b values."
I have tried almost 90%, but somewhere some minor error is breaking my loop, Please help me out.
Sample code:
for(var i=0;i<obj1.results[0].loc.length;i++){
var findA = obj1.results[0].loc[i].anc[0].title;
for(var j=0;j< obj2.ILoc.length;j++){
var findB = obj2.ILoc[j].ais;
if(findA == findB) {
var a = obj1.results[0].loc[i].a;
var b = obj1.results[0].loc[i].b;
console.log(a);
console.log(b);
}
}
}
This is what I have tried:
Demo Link
I would recommend using for...in loop, since you're using objects instead of arrays.
for (variable in object) {...
}
If length property of both objects is equal, then this kind of loop alone will help you to compare objects with ease.
I would recommend using the diff module. You can use it in node.js and the browser.
I'm trying to generate a tree structure in JavaScript from a flat array. This would usually be a fairly straightforward proposition - simply retain a 'stack' array with references to ancestor objects of the current working scope ordered by nesting depth - push a new element onto the stack when entering another nested level, and pop it off when leaving one, replacing the current working element with the object referenced by the (new) last array item.
Unfortunately this requires the capability to pass-by-reference, which JavaScript doesn't have (well, doesn't have in any meaningful way that I know how I could use for this problem.)
To give a bit of background, I'm trying to turn an arbitrarily long/complicated string containing nested XML-style (but not XML, so an XML parser can't be used instead) tokens into a structure similar to the one below:
Expected Input:
[
"<token>",
"<my non compliant token>",
"some text at this level",
"<some other token>",
"some more text",
"<yet another token>",
"more text",
"</yet another token>",
"blah!",
"</some other token>",
"</token>",
"more text"
]
Expected Output
[
{
"token": "<token>",
"children": [
{
"token": "<my non compliant token>",
"children": [
"some text at this level",
{
"token": "<some other token>",
"children": [
"some more text",
{
"token": "<yet another token>",
"children": [ "more text" ]
},
"blah!"
]
}
]
}
]
},
"more text"
]
To clarify - I'm not after an entire algorithm (but I'd be interested if you want to provide your implementation) - just a good method for maintaining current position in the outputted tree (or an entirely different/better way of generating tree objects!) Don't get too caught up on how the tokens work - they're not XML and for the purpose of the exercise could be formatted entirely differently.
Any input would be greatly appreciated!
Your strings look easy to parse. I think I would do something like this:
var stack = [];
var array = [];
for (var i in strings) {
var s = strings[i];
if (s.indexOf("</") == 0) {
array = stack.pop();
} else if (s.indexOf("<") == 0) {
var obj = {token: s, children: []};
array.push(obj);
stack.push(array);
array = obj.children;
} else {
array.push(s);
}
}
Idea #1
Here's an answer you probably weren't anticipating.
Looking at your expect output, I was wondering if it's easiest to just generate JSON and then eval it when you're done. No references at all.
When going through your flat array, you basically have three operations:
You add more data to the current object
You close off the current object
You create a new child object
You can do all three of those fairly easily by just appending the appropriate text onto a JSON string you're building as you iterate through your source array to literally just generate the text you show in your expected output. When done, run that JSON string through eval. You may need a few safety checks to verify that each array and object is closed properly if there are errors in the input, but it should work fine.
Idea #2
You can still use your stack array. I'm not sure exactly why you need to pass by reference, but you can just pass an index into the array around and have everyone modify the master copy of the array that way via index. Using local functions, the master array can be a common data value that is local to your main function, but essentially global to all your sub-functions so they can all shared access to it.
This would look something like this:
function ParseRawData(rawData)
{
var parentScopeArray = []; // main parent scope of objects
function processTag(x)
{
// you can access parentScopeArray directly here and
// and be accessing it by reference
}
// other code or local functions here
}
Idea #3
If you want to pass the array into a function and have the master copy modified (perhaps the reason you're thinking of pass by reference), the javascript design pattern is to pass the array in and return a modified array, replacing the entire original array with the modified one that is returned.
I've got results being returned to a Google Mapping application in the div sidebar. The results are names of businesses that belong to categories that the client wants returned in a certain order. And unfortunately it's not a straight alpha sort. So one category begins with F and the second one with a C and the last three are A's, for example.
So I need my switch, which works, but naturally insists on dropping the values in alpha sorted (as they are returned from the DB that way) order as that's how it encounters them. What's the best way to set this up so I can grab my preferred categories with their associated company names in the arbitrary order the client has asked for?
Thanks!
Can you iterate over the categories in the order you want them in, and find the object to which it is associated?
E.g. (pseudocode)
var categories = [ 'F', 'C', 'A1', 'A2', 'A3' ].map(function (category) {
return businesses.filter(function (business) {
return business.category === category;
});
});
So the missing step in the answer given here was HOW the map would be implemented and HOW the JS snippet could be implemented. Anyway, I ended up having to ask that as a separate question and finally got a nice working example for an answer.
Russ wrote:
The code given looks most likely to be
using the jQuery JavaScript library
that has some useful functions such as
map() for manipulating arrays.
If we go back to the original problem,
you need to order a list of categories
based on the client's preference.
Let's create a an object literal to
map the ordering
var map = {
F : 5,
C : 3,
A1 : 1,
A2 : 4,
A3 : 2
}
We can use this map to order the array
using the sort method
var array = ['F', 'C', 'A1', 'A2', 'A3'];
array.sort(function(a,b) {
return map[a] - map[b];
});
This returns us ["A1", "A3", "C", "A2", "F"]
Anyway, I wanted to make sure this was included on this thread for anyone searching for this issue in the future or anyone following along right now. Thanks for everyone's input!