Javascript updates entire column in boolean matrix - javascript

I'm trying to update a specific index in a boolean matrix but it update the entire column. what might be the problem?
I'm attaching the code here:
const booleanMatrix = Array(5).fill(Array(5).fill(false));
console.log(booleanMatrix);
booleanMatrix[0][0] = true;
console.log(booleanMatrix);
first and second prints:
[
[ false, false, false, false, false ],
[ false, false, false, false, false ],
[ false, false, false, false, false ],
[ false, false, false, false, false ],
[ false, false, false, false, false ]
]
[
[ true, false, false, false, false ],
[ true, false, false, false, false ],
[ true, false, false, false, false ],
[ true, false, false, false, false ],
[ true, false, false, false, false ]
]
I expect it to be:
[
[ true, false, false, false, false ],
[ false, false, false, false, false ],
[ false, false, false, false, false ],
[ false, false, false, false, false ],
[ false, false, false, false, false ]
]

Your code is equivalent to:
const inner = Array(5).fill(false);
const booleanMatrix = Array(5).fill(inner);
Of course when you update inner, it updates on each row, since each row is pointing to the same thing.
You need to do
let x = Array(5).fill(null).map((i) => Array(5).fill(false));
console.log(x);
x[0][0] = true;
console.log(x);

const booleanMatrix = Array(5).fill(Array(5).fill(false));
This fills an array with 5 references to the same array.
Array(5).fill(false) // reference to one array
When you change one array, you're changing all of them, because they're all the same object in memory.
You need to create 5 different arrays and load each one of them:
let booleanMatrix = [
Array(5).fill(false),
Array(5).fill(false),
Array(5).fill(false),
Array(5).fill(false),
Array(5).fill(false)
];
Alternatively:
let booleanMatrix = Array(5).fill("throwAway").map( () => Array(5).fill(false));
This will create 5 unique arrays

Related

How to count the number of trues in an array of boolean values?

function countSheeps(arrayOfSheep) {
let sum = [];
for (let i = 0; i < arrayOfSheep.length; i++) {
if (arrayOfSheep[i] == true) {
sum[i].push(arrayOfSheep[i]);
}
}
return sum.length;
}
var array1 = [
true,
true,
true,
false,
true,
true,
true,
true,
true,
false,
true,
false,
true,
false,
false,
true,
true,
true,
true,
true,
false,
false,
true,
true,
];
console.log(countSheeps(array1));
I'm having trouble counting the number of trues in an array of boolean values. I was expecting counting value must be 17 but it's 0, can anyone please tell me where I am wrong and what I should do to make it work?
reduce is an easy way to count items in an array: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
One version of it takes two parameters: a function, and the initial value of the accumulator.
The function parameter also has two parameters: the current accumulator and an item from the array. It will call this function for every item in the array. The return value will be passed as the accumulator of the next call.
The ternary statement sheep ? acc+1 : acc means if sheep is truthy, return acc+1 else return acc. The return is implicit when declaring an arrow function with no curly braces.
function countSheeps(arrayOfSheep) {
return arrayOfSheep.reduce((acc, sheep) => sheep ? acc+1 : acc, 0)
}
const array1 = [
true,
true,
true,
false,
true,
true,
true,
true,
true,
false,
true,
false,
true,
false,
false,
true,
true,
true,
true,
true,
false,
false,
true,
true,
];
console.log(countSheeps(array1));
It should be arrayOfSheep.length, not arrayOfSheep.lenght.
You need to push to sum array,sum.push(arrayOfSheep[i]).
function countSheeps(arrayOfSheep) {
let sum = [];
for (let i = 0; i < arrayOfSheep.length; i++) {
if (arrayOfSheep[i]) {
sum.push(arrayOfSheep[i]);
}
}
return sum.length;
}
One liner: filter the array and then take the length:
const array1 = [ true, true, true, false, true, true, true, true, true, false, true, false, true, false, false, true, true, true, true, true, false, false, true, true,];
console.log(array1.filter(Boolean).length);
Just need to filter and length that result.
Use const instead of var, Cause the value doesn't change in this situation.
const array1 = [
true,
true,
true,
false,
true,
true,
true,
true,
true,
false,
true,
false,
true,
false,
false,
true,
true,
true,
true,
true,
false,
false,
true,
true,
];
console.log(array1.filter(item => item).length);

Transform JSON form front end so it fits what API expects

I have the following data structure held in state by my React application.
{"assetNum": "SP234",
"eventDate": "2021-08-15 08:30:00Z",
"manufacturers": {
"part1":"mfg1",
"part2":"mfg2",
"part3":"mfg3"},
"part1":{
"inlet":[true, true, true, true, true],
"outlet":[false, false, false, false, false]}
"part2":{
"inlet":[false, false true, true, true],
"outlet":[false, false, false, false, false]}
"part3":{
"suction":[true, true, true, true, true],
"discharge":[false, false, false, false, false]}
}
On the other end I have a .NET API expecting the following data structure:
{"assetNum": "SP234",
"eventDate": "2021-08-15 08:30:00Z",
"details":[
{"part":"part1",
"label":"inlet",
"manufacturer":"mfg1",
"locations":[true, true, true, true, true]},
{"part":"part1",
"label":"outlet",
"manufacturer":"mfg1",
"locations":[false, false, false, false, false]},
{"part":"part2",
"label":"inlet",
"manufacturer":"mfg2",
"locations":[false, false, true, true, true]},
{"part":"part2",
"label":"outlet",
"manufacturer":"mfg2",
"locations":[false, false, false, false, false]},
{"part":"part3",
"label":"suction",
"manufacturer":"mfg3",
"locations":[true, true, true, true, true},
{"part":"part3",
"label":"fischarge",
"manufacturer":"mfg3",
"locations":[false, false, false, false, false]},
]
}
I'm trying to avoid changing the state on the front-end since a lot of other things already depend on it. I'm also trying to avoid changing the API.
How can I go about transforming one object into the other structure anytime the user clicks "SUBMIT"? I was thinking of creating a class with a constructor and a method to generate the other JSON but that might be an overkill? I'm hoping there's a straightforward way to do this in Javascript that I haven't learned yet.
Thanks to all in advance,
Easily achieved using ...
2 x Object.entries
Array#map
and
Array#flatMap
const input = {
"assetNum": "SP234",
"eventDate": "2021-08-15 08:30:00Z",
"manufacturers": {
"part1": "mfg1",
"part2": "mfg2",
"part3": "mfg3"
},
"part1": {
"inlet": [true, true, true, true, true],
"outlet": [false, false, false, false, false]
},
"part2": {
"inlet": [false, false, true, true, true],
"outlet": [false, false, false, false, false]
},
"part3": {
"suction": [true, true, true, true, true],
"discharge": [false, false, false, false, false]
}
};
const output = {
assetNum: input.assetNum,
eventDate: input.eventDate,
details: Object.entries(input.manufacturers).flatMap(([part, manufacturer]) => Object.entries(input[part]).map(([label, locations]) => ({ part, label, manufacturer, locations})))
};
console.log(output);
You can use Object.keys and map your objects
code:
const data = {
"assetNum": "SP234",
"eventDate": "2021-08-15 08:30:00Z",
"manufacturers": {
"part1": "mfg1",
"part2": "mfg2",
"part3": "mfg3"
},
"part1": {
"inlet": [true, true, true, true, true],
"outlet": [false, false, false, false, false]
},
"part2": {
"inlet": [false, false, true, true, true],
"outlet": [false, false, false, false, false]
},
"part3": {
"suction": [true, true, true, true, true],
"discharge": [false, false, false, false, false]
}
};
let model = {
"assetNum": data.assetNum,
"eventDate": data.eventDate,
"details": []
}
Object.keys(data.manufacturers).forEach(key=>{
const row = data[key]
Object.keys(row).forEach(innerKey=>{
let item = {
"manufacturer":data.manufacturers[key],
"part": key,
"label": innerKey,
"locations": row[innerKey]
}
model.details.push(item)
})
})
console.log(model)

Occasionally addMissingImports on save imports React again

I am using typescript and in *.tsx files, especially when i am copying code around, it quite often adds an additional
import React from "react";
// ? On Save
"editor.codeActionsOnSave": {
"source.addMissingImports": true,
"source.fixAll.eslint": true
// "source.organizeImports": true
}
I am using this configuration and works fine.
extensions.json
{
"recommendations": [
"amatiasq.sort-imports",
"dbaeumer.vscode-eslint",
"eamodio.gitlens",
"eg2.vscode-npm-script",
"esbenp.prettier-vscode",
"github.copilot",
"github.vscode-pull-request-github",
"ibm.output-colorizer",
"mhutchie.git-graph",
"ms-azuretools.vscode-docker",
"ms-kubernetes-tools.vscode-kubernetes-tools",
"ms-playwright.playwright",
"ms-vscode-remote.vscode-remote-extensionpack",
"pkief.material-icon-theme",
"quicktype.quicktype",
"redhat.vscode-yaml",
"ryanluker.vscode-coverage-gutters",
"streetsidesoftware.code-spell-checker",
"stylelint.vscode-stylelint",
"tyriar.sort-lines"
]
}
settings.json
{
"[javascript]": {
"editor.formatOnSave": false
},
"[javascriptreact]": {
"editor.formatOnSave": false
},
"[jsonc]": {
"editor.defaultFormatter": "vscode.json-language-features"
},
"[typescript]": {
"editor.formatOnSave": false
},
"[typescriptreact]": {
"editor.formatOnSave": false
},
"diffEditor.ignoreTrimWhitespace": false,
"editor.bracketPairColorization.enabled": true,
"editor.codeActionsOnSave": {
"source.addMissingImports": true,
"source.fixAll": false,
"source.fixAll.eslint": true,
"source.organizeImports": false
},
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnPaste": false,
"editor.formatOnSave": true,
"editor.guides.bracketPairs": "active",
"editor.inlineSuggest.enabled": true,
"editor.suggestSelection": "first",
"editor.tabSize": 2,
"eslint.alwaysShowStatus": true,
"eslint.format.enable": true,
"eslint.probe": [
"html",
"javascript",
"javascriptreact",
"markdown",
"typescript",
"typescriptreact"
],
"files.watcherExclude": {
"**/*.pem": true,
"**/*.tsbuildinfo": true,
"**/.DS_Store": true,
"**/.env.development.local": true,
"**/.env.local": true,
"**/.env.production.local": true,
"**/.env.test.local": true,
"**/.next/**": true,
"**/.pnp.js": true,
"**/.pnp/**": true,
"**/.vercel": true,
"**/build/**": true,
"**/coverage/**": true,
"**/node_modules/**": true,
"**/npm-debug.log*": true,
"**/out/**": true,
"**/yarn-debug.log*": true,
"**/yarn-error.log*": true
},
"github.copilot.enable": {
"*": true,
"markdown": false,
"plaintext": true,
"yaml": true
},
"redhat.telemetry.enabled": true,
"sort-imports.ignore-type-defs": false,
"stylelint.validate": [
"css",
"scss"
],
"terminal.integrated.sendKeybindingsToShell": true,
"window.zoomLevel": 1,
"workbench.iconTheme": "material-icon-theme"
}

Serializing or passing json objects into Ajax

The Json object was returned and I want to extract the data in JavaScript
In the sense of how to pass on the loop fields and extract data
def For_Sale_Listing(request,id):
try:
listing = Listing.objects.filter(pk=id)
listing_json = serializers.serialize("json", listing)
except Listing.DoesNotExist:
raise Http404('listing not found!')
data = {"listing_json": listing_json}
return JsonResponse(data)
$.ajax({
url: "/For-Sale-Listing"+"/" + parseInt(data[0]),
type: "GET",
data: {'Subscription': 1},
success: function(data) {
console.log(JSON.parse(data.listing_json));
},
error: function(xhr, status, error) {
}
});
I want pass to fields with javascript
[{"model": "listings.listing", "pk": 3, "fields": {"property_type": 1, "user": 1, "price": 13000000, "roomsTotal": 78, "Bathrooms": 6, "bedrooms": 67, "Receptionrooms": 67, "livingArea": "67.000", "lotSize": "67.000", "unitType": 1, "yearBuilt": null, "remodelYear": null, "hoaPrice": null, "groundTankSize": null, "garageSize": null, "homeDescription": "", "whatYouLoveDescription": "", "Dishwasher": false, "Dryer": false, "Freezer": false, "GarbageDisposal": false, "Microwave": false, "Oven": false, "Refrigerator": false, "Washer": false, "RadioGroup_Rashan": null, "ACarpet": false, "AConcrete": false, "ATiles": false, "ALinoleum": false, "ADSoftwood": false, "ADOther": false, "BreakfastNook": false, "DiningRoom": false, "FamilyRoom": false, "LaundryRoom": false, "Library": false, "MasterBath": false, "Office": false, "Workshop": false, "roomCount": null, "attic": false, "cableReady": false, "ceilingFan": false, "doublePaneWindows": false, "fireplace": false, "intercom": false, "jettedTub": false, "securitySystem": false, "CCentral": false, "CEvaporative": false, "CGeothermal": false, "CRefrigeration": false, "CSolar": false, "CWall": false, "COther": false, "CNone": false, "HForcedAir": false, "HGeothermal": false, "HHeatPump": false, "HRadiant": false, "HStove": false, "HWall": false, "HOther": false, "FCoal": false, "FElectric": false, "FGas": false, "FOil": false, "FPropaneButane": false, "FSolar": false, "FWoodPellet": false, "FOther": false, "FNone": false, "basketballCourt": false, "doorman": false, "elevator": false, "fitnessCenter": false, "gatedEntry": false, "nearTransportation": false, "tennisCourt": false, "RadioGroup_Architectural": null, "Brick": false, "CementConcrete": false, "Stone": false, "EOther": false, "FloorCount": null, ...
I'm not 100% sure what you are asking, but if you want to read result, you can just use property names from your JSON object. Something like this:
var data = {"model": "listings.listing", "pk": 3, "fields": {"property_type": 1, "user": 1, "price": 13000000, "roomsTotal": 78, "Bathrooms": 6}};
var test = "Model: " + data.model + "<br/>PK:" + data.pk + "<br/> Fields: <br/> Property_Type:" + data.fields.property_type;
------Result----
Model: listings.listing
PK:3
Fields:
Property_Type:1
Fiddler

Finding a key in an object that’s true AND matches en entry in an array

I have an array like this:
baseBreakpoints: [
'xLarge',
'large',
'largeMedium',
'medium',
'smallMedium',
'small',
'xSmall'
]
… and I have an object like this:
breakpoints = {
"gtMedium": true,
"xLarge": true,
"gtLargeMedium": true,
"giant": false,
"small": false,
"ltLargeMedium": false,
"gtLarge": true,
"xSmall": false,
"largeMedium": false,
"medium": false,
"gtSmall": true,
"large": false,
"smallMedium": false
}
I need to find the key in the object that’s true and exists in the array. For example, in this example above the value would be xLarge since xLarge === true in the object and exists in the breakpoints array.
Any suggestions? Lodash is already a dependency in the project, if that helps.
You could filter baseBreakpoints by looking up breakpoints.
var baseBreakpoints = ['xLarge', 'large', 'largeMedium', 'medium', 'smallMedium', 'small', 'xSmall'],
breakpoints = { gtMedium: true, xLarge: true, gtLargeMedium: true, giant: false, small: false, ltLargeMedium: false, gtLarge: true, xSmall: false, largeMedium: false, medium: false, gtSmall: true, large: false, smallMedium: false },
result = baseBreakpoints.filter(k => breakpoints[k]);
console.log(result);
ES5
var baseBreakpoints = ['xLarge', 'large', 'largeMedium', 'medium', 'smallMedium', 'small', 'xSmall'],
breakpoints = { gtMedium: true, xLarge: true, gtLargeMedium: true, giant: false, small: false, ltLargeMedium: false, gtLarge: true, xSmall: false, largeMedium: false, medium: false, gtSmall: true, large: false, smallMedium: false },
result = baseBreakpoints.filter(function (k) { return breakpoints[k]; });
console.log(result);
you can try this approach.
the first condition check if the key is truthy, the second one test if in the array there's a match.
This solution compared to the other correct answers returns a pure string rather then a filtered array.
let baseBreakpoints = ['xLarge', 'large', 'largeMedium', 'medium',
'smallMedium', 'small', 'xSmall'];
let breakpoints = {
"gtMedium": true,
"xLarge": true,
"gtLargeMedium": true,
"giant": false,
"small": false,
"ltLargeMedium": false,
"gtLarge": true,
"xSmall": false,
"largeMedium": false,
"medium": false,
"gtSmall": true,
"large": false,
"smallMedium": false
}
let key = Object.keys(breakpoints).find(key => {
return breakpoints[key]
&& baseBreakpoints.some(breakpoint => breakpoint === key);
})
console.log(key);
Fairly simple lookup
var baseBreakpoints = [
'xLarge',
'large',
'largeMedium',
'medium',
'smallMedium',
'small',
'xSmall'
];
var breakpoints = {
"gtMedium": true,
"xLarge": true,
"gtLargeMedium": true,
"giant": false,
"small": false,
"ltLargeMedium": false,
"gtLarge": true,
"xSmall": false,
"largeMedium": false,
"medium": false,
"gtSmall": true,
"large": false,
"smallMedium": false
}
var res = [];
for (bp of baseBreakpoints) {
if (breakpoints[bp] != undefined && breakpoints[bp]) res.push(bp)
}
console.log(res)

Categories

Resources