I'm trying to add values into 2D array based on the position that is present in the input data.
For example, the below format represents 0 as row, 0 as column and 5 is length of the value.
[
"0,0,5",
"hello"
],
How do I insert the values into 2D array based on position like [0][0], [0][1] and [0][2]?
Except from my code
const data = [
[
"0,0,5",
"hello"
],
[
"0,1,10",
"js is fun!"
],
[
"0,2,0",
""
]
]
let array2D = [
[]
];
let i = 0
for (let r = 0; r < data.length; ++r) {
array2D[r] = [];
for (let c = 0; c < data.length; ++c) {
array2D[r][c] = data[i++];
}
}
console.log(array2D);
Ok, thank you for your input.. it means that I'll just make a function to place into an array with 4 arguments.. col,row,arr&data
//important function
function place2d(row,col,arr,data){
//row col logic works like arr[row][col]
arr[row]=arr[row]||[]
arr[row][col]=data
}
var array2dArray=[]
//this loop would take the data array and place the entire index in the desired destination
data.forEach(a=>{
var [row,col]=a[0].split(',')
place2d(row,col,array2dArray,a) //the data to put into each part of the 2d array would an array itself(like data[0])
})
console.log(array2dArray)
//but I might just wanna put the text in the 2d array
var text2dArray=[]
data.forEach(a=>{
var [row,col]=a[0].split(',')
place2d(row,col,text2dArray,a[1]) //the data to be put in each part of the 2d array would be the a text variable(like data[0][1] is "hello")
})
console.log(text2dArray)
<script>
//sry it just takes space in the js part that's unnessecary
window.data = [
[
"0,0,5",
"hello"
],
[
"0,1,10",
"js is fun!"
],
[
"0,2,0",
""
]
]
</script>
With this function, you can take an empty array, place row 10 col 4 in empty array putting any data like 'xD' and it will work out eg: try place2d(10,4,emptyArrName,"xD") and it works.. just one thing to note..
IT ONLY APPLIES array structures to WHERE IT NEEDS TO.. doing things like the example above would leave a lot of undefined slots.. wild example below
//now for a wild example to show that the function works
window.data2=[
["text for [10][0]","0/10"],
["text for [2][5]","5/2"]
]
//don't forget the placer function :D
function place2d(row,col,arr,data){
//row col logic works like arr[row][col]
arr[row]=arr[row]||[]
arr[row][col]=data
}
//at the end of the day, all I'm changing is the information I make out of the array in the forEach loops in order to simply place in the function
var finalArray=[]
place2d(3,4,finalArray,"randomDataThatCouldBe_ANYTHING_notJustText")
data2.forEach(a=>{
var [col,row]=a[1].split('/')
place2d(row,col,finalArray,a[0])
})
console.log(finalArray)
Related
Good day! I badly need help for this one, I have an array with many elements/data that is needed to be display in textbox. Each array element/data must be inside the textbox. (The Textbox must be dynamically set up using loop with the array data inside it)
arr = ["1"-"2"-"3"-"4"-"5"]; //my array is from the db, this is example only
conv_arr = arr.split("-")
var myArray = [conv_arr];
var ArrayInText = document.createElement('input');
myArray.forEach(function(conv_arr) {
ArrayInText.value = conv_arr ;
document.body.appendChild(ArrayInText);
It displays the array (pretend this is a textbox [ ])
[ 1, 2, 3, 4, 5 ]
I want a result that looks like this (One textbox per element using loop)
[ 1 ] [ 2 ] [ 3 ] [ 4 ] [ 5 ]
You can see the demo here=> https://jsfiddle.net/4ow6k8j5/1/
After removing unnecessary assignments, you can use below simplest solution;
conv_arr = arr.split("-")
conv_arr.forEach(function(elem) {
var ArrayInText = document.createElement('input');
ArrayInText.value = elem ;
document.body.appendChild(ArrayInText);
});
I'm super newbie in coding and I need help to achieve this code.
I'm trying to get a random item (in pairs) from an array and then remove it from this array until user gets to the last item or 60 days have gone from using the service (cookie?)... I have build a script with the help of other questions here in stackoverflow and here is my results so far.
`<script>
var randomizer = document.getElementById("getImgBut");
var dog1 = '/app/wp-content/mediaApp/yo-creo-mi-realidad/01F.jpg';
var dog2 = '/app/wp-content/mediaApp/yo-creo-mi-realidad/01B.jpg';
var dogpics=[dog1,dog2];
var yourPics = [
dogpics,
[ '/app/wp-content/mediaApp/yo-creo-mi-realidad/02F.jpg', '/app/wp-content/mediaApp/yo-creo-mi-realidad/02B.jpg' ],
[ '/app/wp-content/mediaApp/yo-creo-mi-realidad/03F.jpg', '/app/wp-content/mediaApp/yo-creo-mi-realidad/03B.jpg' ],
[ '/app/wp-content/mediaApp/yo-creo-mi-realidad/04F.jpg', '/app/wp-content/mediaApp/yo-creo-mi-realidad/04B.jpg' ],
[ '/app/wp-content/mediaApp/yo-creo-mi-realidad/05F.jpg', '/app/wp-content/mediaApp/yo-creo-mi-realidad/05B.jpg' ],
[ '/app/wp-content/mediaApp/yo-creo-mi-realidad/06F.jpg', '/app/wp-content/mediaApp/yo-creo-mi-realidad/06B.jpg' ] //This array has 52 cards but I cutted it for example purposes
];
function get_random_number(array){
return Math.floor(Math.random() * array.length |0);
} // here is where I have tried to modify with other scripts like the one in this page https://stackoverflow.com/questions/38882487/select-random-item-from-array-remove-it-restart-once-array-is-empty with no success
randomizer.addEventListener("click", function() {
var rand_number = get_random_number(yourPics);
console.log(rand_number);
document.getElementById('img1').src = yourPics[rand_number][0];
document.getElementById('img2').src = yourPics[rand_number][1];
});
var card = document.querySelector('.card');
card.addEventListener( 'click', function() {
card.classList.toggle('is-flipped');
});
</script>`
Thank you for your help!
I don't fully understand what you mean by "remove in pairs", but I'll answer presuming you mean you wish to remove the image ending in 02F.jpg at the same time as removing the image ending in 02B.jpg, and then 03F.jpg at the same time as 03B.jpg.
The solution to this that I will propose is that we will structure your data a bit differently to begin with. That is, if those images, the "B image" and "F image" are linked, we could keep them in the same `javascript object. This would look like:
var yourPics = [
{
bImage: '/app/wp-content/mediaApp/yo-creo-mi-realidad/02F.jpg',
fImage: '/app/wp-content/mediaApp/yo-creo-mi-realidad/02B.jpg'
},
{
bImage: '/app/wp-content/mediaApp/yo-creo-mi-realidad/03F.jpg',
fImage: '/app/wp-content/mediaApp/yo-creo-mi-realidad/03B.jpg'
}...]
This would then be an array of objects, rather than strings. We can access the bImage property of an object with just
myObject = yourPics[0]
myObject.bImage
We could delete one of those objects those at random via splice.
myRandomlyRemovedObject = yourPics.splice(myIndexToDeleteFrom, 1) would remove 1 object from yourPics at position of myIndexToDeleteFrom, which you presumably would choose randomly. myRandomlyRemovedObject would be assigned to the one object we removed.
I think this object based approach is safer since you will know for a fact that you will removed both matching strings at the same time.
I have a list that I took from a converted CHANGELOG.md file, and it looks like this:
["[3.0.0]","Features", "changes done in file","[2.0.1]", "Bug Fixes", "fixed login"]
What I want to do is to separate each version into its own list, like this:
["[3.0.0]", "Features", "changes done in file"],
["[2.0.1]", "Bug Fixes", "fixed login"]
Obviously, because it's a changelog, there can be multiple features and multiple bugfixes in a single version, so I want to a piece of code that separates the code appropriately.
I tried using if (string.startsWith('[')) but i couldn't manage to fit it in a loop.
Any help is appreciated.
Here's something I came up with. The code basically loops through the input array and adds each string to a currentArray variable. Everytime it hits a [ it puts the currentArray into the output and clears currentArray. At the end it removes the first element as the first element of the output will always be an empty array (since the first element of the input starts with a [)
var input = ["[3.0.0]","Features", "changes done in file","[2.0.1]", "Bug Fixes", "fixed login"];
var output = [];
var currentArray = [];
for (var i = 0; i < input.length; i++) {
if (input[i].charAt(0) == '[') {
output.push(currentArray);
currentArray = [];
}
currentArray.push(input[i]);
}
output.push(currentArray);
currentArray = [];
//Since it will take the first one, and put empty one, need to do last step.
output.splice(0, 1);
console.log(output);
// ["[3.0.0]", "Features", "changes done in file"],
// ["[2.0.1]", "Bug Fixes", "fixed login"]
Assuming that you're always working in sets of three, this is a quick and ugly approach
var data = ["[3.0.0]","Features", "changes done in file","[2.0.1]", "Bug Fixes", "fixed login"],
items = [];
data.map( (el, idx) => {
var last = items.length;
if( idx % 3 === 0 ) {
items.push( [] );
last += 1;
}
last = items[ last - 1 ];
last.push( el );
} );
console.log( JSON.stringify( items ) );
Here's an alternative solution should you prefer it:
const arr = ["[3.0.0]","Features", "changes done in file","[2.0.1]", "Bug Fixes", "fixed login"];
const newArr = [];
let tempArr = [];
arr.forEach(function(v, i) {
if(/^\[\d+.\d+.\d\]$/.test(v) && i > 0) {
newArr.push(tempArr);
tempArr = [v];
} else {
tempArr.push(v)
}
});
newArr.push(tempArr);
console.log(newArr);
This snippet loops through the items one-by-one. It uses two arrays, one to hold the final result and one to populate with items for the current version.
I am using a regex to check if the item contains one [ followed by a number, then a period, number, period, number and finally the trailing ]. This allows the other strings that are not version tags to contain that character.
If the current item is a version tag, we push tempArr (which contains the changes of the current version that we've previously filled in our loop) to our result array newArr. Then, we empty the tempArr and give it the starting value of the next version tag.
If it is not, we just push the current item to our temporary array.
It would be interesting to know if you were guaranteed to get this data in triplets, as your example seems to imply. If you knew this up front, there are many creative solutions that could emerge. For just creating a 2D Array, however, I like this approach (you can run this directly in node.js to try it out):
const original = ['[3.0.0]', 'Features', 'changes done in file', '[2.0.1]', 'Bug Fixes', 'fixed login']
function transformToChangeLog (originalArray) {
const changeLog = originalArray.reduce((newList, element) => {
element.charAt(0) === '[' // check for version string
? newList.push([element]) // If version string, then push a new Array containing that string
: newList[newList.length - 1].push(element) // If something else, tack it onto the last Array in the changelog list
return newList // whatever is returned in the reduce function is passed to the next iteration, allowing us to build this 2D array one element at a time.
}, [])
return changeLog
}
console.log(transformToChangeLog(original))
I hope that helps! I like the reduce Array method, because of it's versatility and succinctness.
Still learning... sorry if this doesn't make sense or sounds stupid :P
I have 2 variables "timestamps" and "clicks" and a string of numbers:
{
"timestamps":[
1362096000000,1362355200000,1362441600000,1362528000000
],
"clicks":[
[
1,2,3,4
]
};
What would be the easiest way to reformat the string and output into an array like this:
[1362096000000,1],
[1362355200000,2],
[1362441600000,3],
[1362528000000,4],
Just based on the limited information you've given us, and assuming the constraints of both timestamps and clicks always being the same length of arrays, and that you want the output to be an array this will create the new desired format.
var output = [];
for (var i = 0, l = obj.timestamps.length; i < l; i++) {
output.push([obj.timestamps[i], obj.clicks[i]]);
}
/*output is now [
[1362096000000,1],
[1362355200000,2],
[1362441600000,3],
[1362528000000,4]
]*/
Hi I'm debugging my page for IE8 compat mode, and this script just doesn't like to work and crushes.
Basically it had to iterate through a 3D array, and add a local path to a variable. Well I could do it otherwise, but I'm just curious why the ** it never works...
Any suggestions are welcome :) Here's the code:
for(i=0;i<menu_items_p.length;i++)
for(j=0;j<menu_items_p[i].length;j++)
menu_items_p[i][j][1]='http://127.0.0.1/'+menu_items_p[i][j][1];
and the array looks something like this:
var menu_items_p =
[
[ //Products
['Health Care', 'products/health.php'],
['Aroma Therapy','products/scents.php'],
],
[ // Empty
],
[ //Test
['What ever', 'spirulina/about.php'],
]
]
The problem though is that it sometimes have empty values, and array.length triggers some error...
When used your original array declaration:
var menu_items_p =
[
[ //Products
['Health Care', 'products/health.php'],
['Aroma Therapy','products/scents.php'],
],
[ // Empty
],
[ //Test
['What ever', 'spirulina/about.php'],
]
]
error occurs in IE8 but not in IE9. Just remove two commas:
var menu_items_p =
[
[ //Products
['Health Care', 'products/health.php'],
['Aroma Therapy','products/scents.php'] // here comma removed
],
[ // Empty
],
[ //Test
['What ever', 'spirulina/about.php'] // here comma removed
]
]
and all must work fine.
Maybe your code could handle empty values this way:
for(var i = 0; i < menu_items_p.length; i++) {
// we skip the value if it is empty or an empty array
if(!menu_items_p[i] || !menu_items_p[i].length) continue;
for(var j = 0; j < menu_items_p[i].length; j++) {
// again, we skip the value if it is empty or an empty array
if(!menu_items_p[i][j] || !menu_items_p[i][j].length) continue;
menu_items_p[i][j][1] = 'http://127.0.0.1/' + menu_items_p[i][j][1];
}
}
AS suggested by Yoshi and ThiefMaster, I made it following, and this is what solved it:
for(var i=0;i<menu_items_p.length;i++)
if (menu_items_p[i] !== undefined)
for(var j=0;j<menu_items_p[i].length;j++)
if (menu_items_p[i][j] !== undefined)
menu_items_p[i][j][1]='http://127.0.0.1/'+menu_items_p[i][j][1];
Global vars replaced.
Check for undefined.
It's a pity they didn't answer in a formal way, so I would have to answer my self :)
Thanks everyone!