getting array value in console - javascript

I have an array (tot) with arrays in it.
I need to check each entry in (tot) for a value , which is done at console by typing AA[3] , however, when I execute it from a script, AA[3] would NOT return any value!
here is my script:
tot=["AA","AB","AC"];
AA=["1","2","3","4","5","6","7"];
AB=["1","2","3","4","5","6","7"];
AC=["1","2","3","4","5","6","7"];
for (let i = 0; i < tot.length; i++)
{
tot[i]+'[2]';
}

I have an array (tot) with arrays in it
Actually that's inaccurate. You have an array with string values inside that are not arrays. The values of the strings you have in your array match the names of some arrays. Instead of this you might want to use an object of arrays, like:
let AA=["1","2","3","4","5","6","7"];
let AB=["1","2","3","4","5","6","7"];
let AC=["1","2","3","4","5","6","7"];
let tot={AA,AB,AC};
let index = 5;
for (let key in tot) {
console.log(`${key}[${index}]: ${tot[key][index]}`);
}

You could try:
const tot = [
["1","2","3","4","5","6","7"],
["1","2","3","4","5","6","7"],
["1","2","3","4","5","6","7"]
];
for (let i = 0; i < tot.length; i++)
{
console.log(tot[i][2]);
}

Variables do not work as functions. Instead of writing variables in a loop, try:
console.log(tot);
Also, I assume you meant to do var tot = new Array(AA, AB, AC);
var AA=["1","2","3","4","5","6","7"];
var AB=["1","2","3","4","5","6","7"];
var AC=["1","2","3","4","5","6","7"];
var tot= new Array(AA,AB,AC);
for (let i = 0; i < tot.length; i++)
{
tot[i].push("2")
console.log(tot[i]);
}

To loop through every array inside tot array, you have to nest two for loops, and console.log each value in nested for loop:
const AA=["1","2","3","4","5","6","7"];
const AB=["1","2","3","4","5","6","7"];
const AC=["1","2","3","4","5","6","7"];
const tot=[AA,AB,AC];
const logArray = (tot) => {
for (let i = 0; i < tot.length; i++) {
console.warn(`tot[${i}] contains:`);
for (let j = 0; j < tot[i].length; j++) {
console.log(tot[i][j]);
}
}
};

Your code doesn't output anything, because you didn't ask it to. also that line: tot[i] + '[2]' is not correct. What exactly are you trying to do there. I changed it to add '[2]' string to each element, but doesn't seem that that is what you want.
tot=["AA","AB","AC"];
AA=["1","2","3","4","5","6","7"];
AB=["1","2","3","4","5","6","7"];
AC=["1","2","3","4","5","6","7"];
for (let i = 0; i < tot.length; i++)
{
tot[i]+='[2]';
}
console.log(tot)

Related

JavaScript Add item to array if its not already exist

How can I check in JavaScript if the array already have the item?
Im adding the items to my array with the next code:
const booked_hours = [];
for (let i = 0; i < apptid_set.size; i++) {
const book_hours = [...book_times][i].split(" ");
booked_hours.push(book_hours[2]);
}
//alert(booked_hours);
Its works well, just in the booked_hours shouldnt be any duplicated item.
How can I do that?
Without knowing what you're adding to the booked_hours array this answer might have to be tweaked but take a look at this.
const booked_hours = [];
for (let i = 0; i < apptid_set.size; i++) {
const book_hours = [...book_times][i].split(" ");
if (!booked_hours.includes(book_hours[2])) {
booked_hours.push(book_hours[2]);
}
}
You can use a set instead of an array for booked_hours
const booked_hours = new Set();
for (let i = 0; i < apptid_set.size; i++) {
const book_hours = book_times[i].split(' ');
booked_hours.add(book_hours[2]);
}
And to convert it back to an array you can do [...booked_hours]

Js Math.random not random [duplicate]

I tried to get this to work, but the outer loop stops after second iteration, and everything that's after it does not execute(just like it was the end of the script). I want to fill two dimensional array with any character(here i used 'q' as an example)
var A=[[],[]];
for(var i=0;i<12;i++){
for(var j=0;j<81;j++){
A[i][j]='q';
}
}
It didn't work, so i put alert(i+' '+j); to see if it's even executing, and, as i wrote before, it stops after second iteration of outer loop, and then ignores rest of the script.
All I want is to have this array filled with same character in the given range(12 rows, 81 columns in this specific case), so if there's no hope in this method, i'll be glad to see one that works.
This does the job in one line.
var A = Array(12).fill(null).map(()=>Array(81).fill('q'))
This is an array of references and a bad idea as harunurhan commented.
var A = Array(12).fill(Array(81).fill('q'));
The Array.from() method creates a new, shallow-copied Array instance
from an array-like or iterable object.
function createAndFillTwoDArray({
rows,
columns,
defaultValue
}){
return Array.from({ length:rows }, () => (
Array.from({ length:columns }, ()=> defaultValue)
))
}
console.log(createAndFillTwoDArray({rows:3, columns:9, defaultValue: 'q'}))
var A=[[], []];
^ This line declares a two dimensional array of size 1x2. Try this instead:
var A = [];
for (var i = 0; i < 12; i++) {
A[i] = [];
for (var j = 0; j < 81; j++) {
A[i][j] = 'q';
}
}
Since fill() is the most succinct and intuitive, and it works as intended for immutable values, my preference would be an outer from() and an inner fill():
Array.from({length: 12}, _ => new Array(81).fill('q'));
The best approach to fill up 2D array would be like the following
let array2D = [], row = 3, col = 3, fillValue = 1
for (let i = 0; i < row; i++){
let temp = []
for (let j = 0; j < col; j++){
temp[j] = fillValue
}
array2D.push(temp)
}
You need to initialise a new array for i each time the first loop runs, and you don't need to set the layout of the array before you create it (Remove the [], [] inside the declaration of A). Try this:
var A = [];
for (var i = 0; i < 12; i++) {
A[i] = [];
for (var j = 0; j < 81; j++) {
A[i][j] = 'q';
}
}
console.log(A);
.as-console-wrapper {
max-height: 100% !important;
top: 0;
}

Grabbing String From Nested Array Using Nested Loops

I am a totally new to coding and I'm practicing loops and arrays. I created an array with multiple sub arrays that contain pairs of strings. I'm trying to pull out and isolate each string using a nested for loops.
Here is my code:
const pairs = [['Blue', 'Green'],['Red', 'Orange'],['Pink', 'Purple']];
//attempting to use nested arrays to get each string from an array
function getString(arr){
//this loop should grab each array in the list of arrays
for (let i = 0; i < arr.length; i++){
console.log(i , arr[i]);
//this should assign each sub array to a new var to be iterated over
subArr = arr[i];
} for (let j = 0; j < subArr.length; j++){
console.log(j, arr[j]);
}
};
console.log(getString(pairs));
the problem is the output is of the last for loop is : ['Pink', 'Purple'] not each color extracted from the nested loops.
What am I doing wrong here?
Mirii
You should nest the for loops like this:
for (let i = 0; i < arr.length; i++) {
console.log(i, arr[i]);
//this should assign each sub array to a new var to be iterated over
subArr = arr[i];
for (let j = 0; j < subArr.length; j++) {
console.log(j, arr[j]);
}
}
How you have it, they'd run one after the other.
The solution is provided
:
function getString(arr) {
let arrResult = [];
for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < arr[i].length; j++) {
arrResult.push(arr[i][j]);
}
}
return arrResult;
}
You need to nest the loops, just like you are nesting the arrays. Also, unless you want to alter i or j, I suggest you use .forEach as it is more simple to work with.
Example:
pairs.forEach((pair, i) => {
pair.forEach((subPair, j) => {
console.log(j, subPair);
});
});
You may also make a variable, push to it within the pair.forEach function, and return it at the end of your root function.
I hope this answers your question, thank you for posting, and have a nice day. ;P
Your loops aren't actually nested: you close the first loop before starting the second one. Because subArr is a global varialbe (no let, const, or var keyword), it's still defined in the second loop, but that's not an ideal way to do things. You also need to log arr[i][j] rather than what you have.
This fixes those issues:
function getString(arr) {
//this loop should grab each array in the list of arrays
for (let i = 0; i < arr.length; i++){
//this should assign each sub array to a new var to be iterated over
let subArr = arr[i];
for (let j = 0; j < subArr.length; j++){
console.log(arr[i][j]);
}
}
};
getString(pairs);
Another issue you have is that you're calling console.log(getString(pairs)), but getString doesn't return anything, it's logging itself. If you want it to return, for example, a newline-delimited string of all the items, you could push items to an array and return them joined with a newline (or whatever character you want):
function getString(arr) {
let ret = []
//this loop should grab each array in the list of arrays
for (let i = 0; i < arr.length; i++){
//this should assign each sub array to a new var to be iterated over
let subArr = arr[i];
for (let j = 0; j < subArr.length; j++){
ret.push(arr[i][j]);
}
}
return ret.join('\n')
};
console.log(getString(pairs));
Nested loops themselves aren't ideal, since they're not as readable as using array methods. Using forEach takes much less code:
function getString (arr) {
arr.forEach(function (subArr) {
console.log(subArr[0])
console.log(subArr[1])
})
}
getString(pairs)
Or, more succinctly, you can use map:
function getString (arr) {
return arr.map(([ a, b ]) => `${a}\n${b}`).join('\n');
}
console.log(getString(pairs))
Even more succinctly, you can do this with [].flat():
const getString = (xs = []) => xs.flat().join('\n')
console.log(getString(pairs))

How to fill multidimensional array in javascript?

I tried to get this to work, but the outer loop stops after second iteration, and everything that's after it does not execute(just like it was the end of the script). I want to fill two dimensional array with any character(here i used 'q' as an example)
var A=[[],[]];
for(var i=0;i<12;i++){
for(var j=0;j<81;j++){
A[i][j]='q';
}
}
It didn't work, so i put alert(i+' '+j); to see if it's even executing, and, as i wrote before, it stops after second iteration of outer loop, and then ignores rest of the script.
All I want is to have this array filled with same character in the given range(12 rows, 81 columns in this specific case), so if there's no hope in this method, i'll be glad to see one that works.
This does the job in one line.
var A = Array(12).fill(null).map(()=>Array(81).fill('q'))
This is an array of references and a bad idea as harunurhan commented.
var A = Array(12).fill(Array(81).fill('q'));
The Array.from() method creates a new, shallow-copied Array instance
from an array-like or iterable object.
function createAndFillTwoDArray({
rows,
columns,
defaultValue
}){
return Array.from({ length:rows }, () => (
Array.from({ length:columns }, ()=> defaultValue)
))
}
console.log(createAndFillTwoDArray({rows:3, columns:9, defaultValue: 'q'}))
var A=[[], []];
^ This line declares a two dimensional array of size 1x2. Try this instead:
var A = [];
for (var i = 0; i < 12; i++) {
A[i] = [];
for (var j = 0; j < 81; j++) {
A[i][j] = 'q';
}
}
Since fill() is the most succinct and intuitive, and it works as intended for immutable values, my preference would be an outer from() and an inner fill():
Array.from({length: 12}, _ => new Array(81).fill('q'));
The best approach to fill up 2D array would be like the following
let array2D = [], row = 3, col = 3, fillValue = 1
for (let i = 0; i < row; i++){
let temp = []
for (let j = 0; j < col; j++){
temp[j] = fillValue
}
array2D.push(temp)
}
You need to initialise a new array for i each time the first loop runs, and you don't need to set the layout of the array before you create it (Remove the [], [] inside the declaration of A). Try this:
var A = [];
for (var i = 0; i < 12; i++) {
A[i] = [];
for (var j = 0; j < 81; j++) {
A[i][j] = 'q';
}
}
console.log(A);
.as-console-wrapper {
max-height: 100% !important;
top: 0;
}

Looping all objects in an array

I have an array of data as follows:
var Sonuc = [[{"ID":8,"Number":"1","Name":"Ahmet"}],
[{"ID":7,"Number":"2","Name":"Semih"}],
[{"ID":6,"Number":"3","Name":"Derviş"}],
[{"ID":8,"Number":"4","Name":"Derviş"},{"ID":9,"Number":"4","Name":"Veli"}],
[{"ID":11,"Number":"44","Name":"Zeki"},{"ID":45,"Number":"44","Name":"Veli"}]]
I tried to write datas to console for each object as follows, but it does not work:
for (var i = 0; i < 3; i++) {
for(var obj in Sonuc[i]) {
console.log(obj.Number);
};
}
How can I output the Number value for each data on console?
The problem is that you have an array or arrays, with the sub-arrays each containing one or more objects.
Your problem is you are not specifying the index for the sub-arrays. You can access the first object like this:
console.log(obj[0].Number);
That will get you some output at at least, but it is confusing exactly what data you want to get. That 3 loop makes no sense...
If you want to output all objects, then you should first loop the sub-arrays, and then loop the objects. Something like this:
var Sonuc = [[{"ID":8,"Number":"1","Name":"Ahmet"}],
[{"ID":7,"Number":"2","Name":"Semih"}],
[{"ID":6,"Number":"3","Name":"Derviş"}],
[{"ID":8,"Number":"4","Name":"Derviş"},{"ID":9,"Number":"4","Name":"Veli"}],
[{"ID":11,"Number":"44","Name":"Zeki"},{"ID":45,"Number":"44","Name":"Veli"}]];
for (var i = 0; i < Sonuc.length; i++) {
var arr = Sonuc[i];
for (var j = 0; j < arr.length; j++) {
var obj = arr[j];
console.log(obj.Number);
}
}

Categories