2d array with function javascript - javascript

I've task to create function that will display names from 2d array (const users). Each name should be displayed in separate line in console. Here is the code I've prepared but not sure if it's correct?
const users = [["Jaydn Humphries", "Ayda Orozco"], ["Sanjeev Wilkinson", "Jorge Markham"]];
function print2DArray(array) {
for(let i = 0; i < array.length; i++){
for(let j = 0; j < array.length; j++) {
console.log(array[i][j]);
}
}return array;
}
print2DArray(users);

Your inner for loop should run on the inner array not on the outer array.
i.e. j should be looped up to array[i].length not array.length
Although since in your example the inner arrays have the same length as the outer array, your example should work just fine.

Related

Loop thought a multi dimensional array

I try to return a multidimensional array into a function to iterate it but I'm not sure what's wrong with my logic
const arr = [[1,2], [3,4],[5,6]]
for(let i = 0; i < thirdInterval.length-1; i++){
getNumbers(thirdInterval[i], thirdInterval[i+1])
}
The result that I want to achieve is return the first element into the first argument of the function and the second element of the array into the second argument of the function.
What you are doing here is looping through the array and getting only the array at the index i, e.g arr[0] which is [1,2]. and (thirdInterval[i], thirdInterval[i+1]) is actually equals to ([1,2], [3,4])
to access the first and second elements you should address them like the following:
for(let i = 0; i < thirdInterval.length-1; i++){
getNumbers(thirdInterval[i][0], thirdInterval[i][1])
}
const arr = [[1,2][3,4][5,6]];
for (var i = 0; i < arr.length; i++;) {
func(arr[i][0], arr[i][1];
}
You are iterating an array with sub-arrays, which means that thirdInterval[i] contains two items. You can get the items using the indexes thirdInterval[i][0] and thirdInterval[i][1], but since you're calling a function with those values, you can use spread instead - getNumbers(...thirdInterval[i]).
In addition, the loop's condition should be i < thirdInterval.length if you don't want to skip the last item.
Demo:
const thirdInterval = [[1,2],[3,4],[5,6]]
const getNumbers = console.log // mock getNumbers
for (let i = 0; i < thirdInterval.length; i++) {
getNumbers(...thirdInterval[i])
}

How to compare all elements from two different arrays, programmatically

how can i make it so that my first loop loops through my first array and then another loop loops through the second array and compares the each of the element of the first array to all of the elements of the second array.
ex.
//first loop looping through my array1
for (var i = 0; i < array1.length; i++) {
//to store the element in
var test = array1[i]
//second loop looping through my array 2
for (var j = 0; j < array2.length; i++) {
//compares the current element in the array 1 to all the elements in array 2
if (test == array2[j]) {
alert(array2[j])
}
}
}
so basically i want it so that while the first loop is in the first element example array1[0] the next loop should compare array1[0] to all the elements present in the array2 and after its done that the next element array1[1] should be next to compare.
but when i run this it just alerts the first element of array 1 infinitely
If you want to find the common elements of each array and alert it, here's the solution.
const arrayOne = [16, 26, 41];
const arrayTwo = [10, 12, 26];
for (const element of arrayOne) {
if (arrayTwo.includes(element)) {
alert(element);
}
}
You have only one mistake. I can't comment because I don't have a reputation 50.
In your second loop put j++ instead of i++
you don't need test variable to compare
for (var i = 0; i < array1.length; i++) {
for (var j = 0; j < array2.length; j++) {
if (array1[i]== array2[j]) {
alert(array2[j])
}
}
}
And next time please ask questions clearly.

How to loop through all possible pairs of JSON object keys exactly once?

Say that I have a data structure of n elements and a function check(element1, element2) which performs some kind of checkup on two elements. I need to check exactly all possible pairs of elements. Using combinatorics it is easy to deduce that we need to perform exactly 'n choose 2' binomial coefficient iterations ( n*(n-1)/2 iterations)
So if my data structure is an array, the following nested loops would work:
for(let i = 0; i < elements.length; i++) {
for(let j = i + 1; j < elements.length; j++) {
check(elements[i], elements[j]);
}
}
This way we check the first element with all the others, the second element with elements 3 to n (since we already checked it with the first one), the third with elements 4 to n and so on and so forth. However if 'elements' was a JSON where the key to each element is not an integer, how can we achieve this effect? Obviously we can ensure that we perform all checkups with the following code:
for(var key1 in elements) {
for(var key2 in elements) {
if(key1 != key2) {
check(elements[key1], elements[key2]);
}
}
}
However obviously we are doing a lot of checkups more than once resulting in n^2 iterations.
What method can I use to achieve the same result as in the example with the array?
If you put all the keys you're going to be looping into an array using Object.keys() then you can use your standard for loop to "skip" over previously seen keys like so:
const keys = Object.keys(elements);
for(let i = 0; i < keys.length; i++) {
const key1 = keys[i];
for(let j = i + 1; j < keys.length; j++) {
const key2 = keys[j];
check(elements[key1], elements[key2]);
}
}
Perhaps you could get the list of keys in an array:
let elements = { a: 1, b: 2, c: 3 };
let keys = Object.keys(elements).sort(); // Sorts the keys array alphabetically, and thus simulating the numbers example and be sure you're not repeating "lower" order key after passing it
for(let i = 0; i < keys.length; i++) {
for(let j = i + 1; j < keys.length; j++) {
// check(elements[keys[i]], elements[keys[j]]);
console.log(elements[keys[i]], elements[keys[j]])
}
}
output:
1 2
1 3
2 3

How to delete characters that appear more than once in a string

for(var i=0; i <array.length;i++){
for(var j=1; j<=array.length;j++)
if(array[i]==array[j]) array.splice(j,1)
}
Have been trying using the code above but it just deletes every other char.
My way would be to convert it into a Set and then to an Array and then join to get the final Stirng back.
let a = 'aaabbbcdddd';
console.log(Array.from(new Set(a)).join(''));
Straightforward method with join and Spread syntax (...) by utilising uniqueness property of Set
let a = 'aaabbbcdddd';
console.log([...new Set(a)].join(''));
The Set object lets you store unique values of any type
We are giving string(which is iterable) to initiate the Set, which will remove all duplicates from it. Then we are converting it back to an array with Spread syntax (...). Finally, join the array back together to make it a string.
Your iterators i and j will incorrectly overlap. You should instead start your j iteration at i+1.
let str = 'the hippos are singing';
let array = [...str];
for (var i = 0; i < array.length; i++) {
for (var j = i + 1; j <= array.length; j++)
if (array[i] === array[j])
array.splice(j, 1)
}
console.log(array.join(''));

FreeCodeCamp Chucky Monkey

Problem: Write a function that splits an array (first argument) into groups the length of size (second argument) and returns them as a two-dimensional array.
Why doesn't this work instead? for(var i = 0; i < arr.length; i+=size)
function chunkArrayInGroups(arr, size) {
// Break it up
// It's already broken :(
arr = arr.slice();
var arr2 = [];
for(var i = 0, len = arr.length; i < len; i+=size)
{
arr2.push(arr.slice(0, size));
arr = arr.slice(size);
}
return arr2;
}
Its because every time for loop runs, the size of array is changed, and you are using the changed array length again in your loop.
So you keep a variable pointer to the length of array outside the loop so that you dont loose track of original array length

Categories

Resources