How to read array elements into given object in JS - javascript

i am trying to read the array elements into the object as follows
function points(games){
let scoreBoard = {};
for(let i = 0 ; i < games.length ; i++){
let otherTeam = 0;
let ourTeam = games[i][0];
for(let j = 0 ; j < games[i].length; j++){
otherTeam = games[i][j];
}
scoreBoard[ourTeam] = otherTeam;
}
return scoreBoard;
}
console.log(points(["1:0","2:0","3:0","4:0","2:1","3:1","4:1","3:2","4:2","4:3"]));
I want it to read in in the [x:y] format, i am missing something. Can you please help me ?

The reason is that you defined result as let scoreBoard = {},it's an object and it stores values based on key,but you have multiple duplicate key,such as 4:1,4:2,4:3,the key of them are 4,so the last record will override the previous one.
In order to store all the scores,there are multiple options,such as make the key unique or using array to store it
function points(games){
let scoreBoard = [];
for(let i = 0 ; i < games.length ; i++){
let otherTeam = 0;
let ourTeam = games[i][0];
for(let j = 0 ; j < games[i].length; j++){
otherTeam = games[i][j];
}
scoreBoard.push({[ourTeam]:otherTeam})
}
return scoreBoard;
}
console.log(points(["1:0","2:0","3:0","4:0","2:1","3:1","4:1","3:2","4:2","4:3"]));

Related

Why do arrays within an array, which are the same, not show as the same? [duplicate]

This question already has answers here:
Why doesn't equality check work with arrays [duplicate]
(6 answers)
Why are two identical objects not equal to each other?
(9 answers)
Closed 4 months ago.
I'm sorry in advance that this code is super messy and inefficient, I am just learning, however I am concerned with one particular problem which I have outlined at the bottom.
The aim of this function is to return every unique array with no repetition of elements, from when every element of ArrTwo is put on the end of each element from arrOne.
function multOrdProduct(arrOne,arrTwo){
let backSet = [];
let finalSet = [];
let count = 0;
let tempArr = new Array(arrOne.length);
let permArrOne = [];
let permArrTwo = [];
let pushed;
let setPart = [];
let tempBackSort = [];
for(i=0; i < arrOne.length; i++){
permArrOne.push(arrOne[i]);
}
for(i = 0; i < arrOne.length;i++){
for(j = 0; j < arrTwo.length; j++){
setPart = permArrOne[i].map( x => x);
setPart.push(arrTwo[j]);
backSet.push(setPart);
}
}
// This makes backSet into the array which has every combination of the two arrays when all elements from arrTwo are put onto each element of arrOne
console.log(backSet);
count = 0;
for(z= 0; z < backSet.length - 1; z++){
backSet[count].sort();
tempBackSort = [];
for(k = 0;k < backSet[count].length - 1; k++){
if(tempBackSort.includes(backSet[count][k])){
backSet = backSet.filter(arr => (new Set(arr)).size == arr.length);
kon = 0;
break;
} else{
tempBackSort.push(backSet[count][k]);
kon = 1
}
}
if(kon===1){
count++;
}
backSet[count].sort();
}
// ^^ This filters out every array within backSet which has multiple of the same element
console.log(backSet);
let twoTempArr = backSet;
console.log(backSet[0] === backSet[2]);
return twoTempArr;
}
unArray = [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
duArray = [1,2,3,4]
console.log(multOrdProduct(unArray,duArray));
function multOrdProduct(arrOne,arrTwo){
let backSet = [];
let finalSet = [];
let count = 0;
let tempArr = new Array(arrOne.length);
let permArrOne = [];
let permArrTwo = [];
let pushed;
let setPart = [];
let tempBackSort = [];
for(i=0; i < arrOne.length; i++){
permArrOne.push(arrOne[i]);
}
for(i = 0; i < arrOne.length;i++){
for(j = 0; j < arrTwo.length; j++){
setPart = permArrOne[i].map( x => x);
setPart.push(arrTwo[j]);
backSet.push(setPart);
}
}
// This makes backSet into the array which has every combination of the two arrays when all elements from arrTwo are put onto each element of arrOne
console.log(backSet);
count = 0;
for(z= 0; z < backSet.length - 1; z++){
backSet[count].sort();
tempBackSort = [];
for(k = 0;k < backSet[count].length - 1; k++){
if(tempBackSort.includes(backSet[count][k])){
backSet = backSet.filter(arr => (new Set(arr)).size == arr.length);
kon = 0;
break;
} else{
tempBackSort.push(backSet[count][k]);
kon = 1
}
}
if(kon===1){
count++;
}
backSet[count].sort();
}
// ^^ This filters out every array within backSet which has multiple of the same element
console.log(backSet);
let twoTempArr = backSet;
console.log(backSet[0] === backSet[2]);
return twoTempArr;
}
unArray = [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
duArray = [1,2,3,4]
console.log(multOrdProduct(unArray,duArray));
The problem which I am having is that console.log(backSet[0] === backSet[2]); does not show true, even though when backSet is printed you can see that the first and third elements are the same. Are arrays within an array not equal if they have been sorted?

Initializing and creating an array in Javascript

I want to make an array w[i][j] where each w[i][j] is itself an array of numbers.
If I try to do it naively by declaring an empty array w
and assigning variable by looping through it I get the error:
const w : Array<Array<Array<number>>> = [];
for(let i = 0; i < N; i++){
for(let j = 0; j < N; j++){
w[i][j] = [1,2,3];
}
}
TypeError: Cannot set property '0' of undefined.
Instead I am forced to initialze each element of the array to be empty, using the below code. Only after doing this am I able to make the array with no problems. This can't be the best practice. What am I misunderstanding and what should I write instead?
const w : Array<Array<Array<number>>> = [];
for(let i = 0; i < N; i++){
w[i] = [];
for(let j = 0; j < N; j++){
w[i][j] = [];
}
}
You are getting the error because w[i] is not set when you are trying to set w[i][j].
Fix
Do an init or load in the loop e.g.
const N = 5;
const w: Array<Array<Array<number>>> = [];
for (let i = 0; i < N; i++) {
w[i] = w[i] || [];
for (let j = 0; j < N; j++) {
w[i][j] = [1, 2, 3];
}
}
console.log(w); // All good 🌹

unable to loop the object in Angular

I have a data like below
data = ["I253,J665,l2575"]
and I need the the results like
I253,
J665,
l2575
when i tried to use for in i am getting like I253,J665,l2575 and I tried for loops also but not getting the result
let data = ["I253,J665,l2575"]
for (let i = 0; i > this.data.length; i++) {
console.log(i)
}
for (let x of this.data) {
console.log(x)
}
tried converting the data in to string and then using split changed into array but then also i am getting typeof object only
below is my stack blitz url =: https://stackblitz.com/edit/angular-ivy-drf1dk?file=src/app/app.component.ts
Modify your data variable like below:
data = ["I253", "J665", "l2575"];
for(let i = 0; i < this.data.length; i++){
console.log(this.data[i]);
}
If you have data variable as data = ["I253,J665,l2575"];
Then split it first and then loop through the generated array:
const arr = data[0].split(',');
for(let i = 0; i < arr.length; i++){
console.log(arr[i] + ',');
}
You were having multiple mistakes. First one was with for condition it should be i < this.data.length not i > this.data.length. Then you need to split and loop over it with for (let j = 0; j < data[i].split(',').length; j++) so data[i].split(',')[j] will return expected value.
In case of 2nd for...of loop you were simply logging whole value. Here also you need to split inside for...of and use one more loop to log.
Alternatively you can also use flatMap and loop over it like for (let m of data.flatMap(x => x.split(','))).
Try it below. You can use this.data, but it won't work in below example so it is used as simply data.
let data = ["I253,J665,l2575"];
console.log("Using for loop");
for (let i = 0; i < data.length; i++) {
for (let j = 0; j < data[i].split(',').length; j++) {
console.log(data[i].split(',')[j]);
}
}
console.log("Using for...of loop");
for (let x of data) {
for (let y of x.split(',')) {
console.log(y);
}
}
console.log("Using flatMap");
for (let m of data.flatMap(x => x.split(','))) {
console.log(m);
}
Two ways to solve this.
Also note that your loop is wrong SHOULD NOT BE '>' and Should Be '<'
1. Your data is at array index zero so if you are to keep the data as is
let data = ["I253,J665,l2575"]
let splits = data[0].split(',')
for (let i = 0; i < splits.length; i++) {
console.log(splits[i])
}
or
let data = ["I253,J665,l2575"]
let splits = data[0].split(',')
for (let element of splits) {
console.log(element )
}
2. Fix the data string
let dataString = "I253,J665,l2575"
let splits = dataString.split(',')
for (let i = 0; i < splits.length; i++) {
console.log(splits[i])
}
or
let dataString = "I253,J665,l2575"
let splits = dataString.split(',')
for (let element of splits) {
console.log(i)
}
Clone of the example provided in question
https://stackblitz.com/edit/angular-ivy-izj7up

Shift() elements from an array and push() into another

I'm trying to do something like drawing cards.
I have an array with 52 elements (deck[]), and I want to remove the first 13 elements and put them into another array, lets say player1[].
Then remove the next 13 elements and put them into player2[]...and so on.
I did this:
var deck = [], player1 = [], player2 = [], player3 = [], player4 = [];
function distributeCards(){
for(var i = 1; i < 5; i++){
for(var j = 0; j < 13; j++){
player+i.push(deck.shift(j));
}
}
}
The array variables are declared outside, because I have to access them in other functions.
It says player is not defined...how should I write this?
You can't make up variable name with that. Instead, you should consider using array to store player's card, so you can dynamically reference each of the player's deck like this:
var deck = [];
var numOfPlayers = 4;
var players = new Array(numOfPlayers);
function distributeCards(){
for(var i = 0; i < numOfPlayers; i++){
players[i] = [];
for(var j = 0; j < 13; j++){
players[i].push(deck.shift(j));
}
}
}

Handling multidimentional array in java script is not working

function split(str)
{
var array = str.split(';');
var test[][] = new Array();
for(var i = 0; i < array.length; i++)
{
var arr = array[i].split(',');
for(var j = 0; j < arr.length; j++)
{
test[i][j]=arr[j];
}
}
}
onchange="split('1,2,3;4,5,6;7,8,9;a,b,c;d,e,f;g,h,i')"
it was not working. i need to split this string to 6*3 multi dimentional array
var array[][] = new Array() is not valid syntax for declaring arrays. Javascript arrays are one dimensional leaving you to nest them. Which means you need to insert a new array into each slot yourself before you can start appending to it.
Like this: http://jsfiddle.net/Squeegy/ShWGB/
function split(str) {
var lines = str.split(';');
var test = [];
for(var i = 0; i < lines.length; i++) {
if (typeof test[i] === 'undefined') {
test[i] = [];
}
var line = lines[i].split(',');
for(var j = 0; j < line.length; j++) {
test[i][j] = line[j];
}
}
return test;
}
console.log(split('a,b,c;d,e,f'));
var test[][] is an invalid javascript syntax.
To create a 2D array, which is an array of array, just declare your array and push arrays into it.
Something like this:
var myArr = new Array(10);
for (var i = 0; i < 10; i++) {
myArr[i] = new Array(20);
}
I'll let you apply this to your problem. Also, I don't like the name of your function, try to use something different from the standards, to avoid confusion when you read your code days or months from now.
function split(str)
{
var array = str.split(';'),
length = array.length;
for (var i = 0; i < length; i++) array[i] = array[i].split(',');
return array;
}
Here's the fiddle: http://jsfiddle.net/AbXNk/
var str='1,2,3;4,5,6;7,8,9;a,b,c;d,e,f;g,h,i';
var arr=str.split(";");
for(var i=0;i<arr.length;i++)arr[i]=arr[i].split(",");
Now arr is an array with 6 elements and each element contain array with 3 elements.
Accessing element:
alert(arr[4][2]); // letter "f" displayed

Categories

Resources