javascript check if array key is set - javascript

var place = []
place[0] = "Sant Marti de Canals";
place[1] = "Catalonia";
place[3] = "";
place[4] = "Spain";
placeTitle = place.join(",");
current output is "Sant Marti de Canals,Catalonia,,,Spain"
how can it be "Sant Marti de Canals,Catalonia,Spain"

You can also define a filter function, which is useful in many other situations.
Array.prototype.filter = function(p) {
var a = [];
p = p || function (x) {return x;}
for (var i = 0; i<this.length; ++i) {
if (p(this[i])) {
a.push(this[i]);
}
}
return a;
}
...
placeTitle = place.filter().join(', ');

Writing your own code for this can help
var place = []
place[0] = "Sant Marti de Canals"; place[1] = "Catalonia"; place[3] = ""; place[4] = "Spain";
var placeTitle ='';
for(var test in place) {
placeTitle += place[test]!=''?place[test]+',':'';
}
placeTitle = placeTitle.substr(0,placeTitle.length-1)

placeCopy=[];
for(var i=0;i<place.length;i++){
if(typeof place[i] != 'undefined' && place[i].length > 0){
placeCopy.push(place[i]);
}
}
placeTitle = placeCopy.join(",");

Related

How could i get the result as trie format? object to string format from this code.

My expected output is ["Mark", "Mary", "Martod", "Mariam", "Marg"]
Getting output in console is ["Mark", "Mary", "Mart", "Mari", "Marg"]
How could I get the output as my expected result from this code? Can anyone do this for me?
function get_suggestion_array_from_object(searchstring, current_object) {
var suggestion_array = [];
suggestion_array.push(searchstring);
// console.log(suggestion_array);
append_object_key(suggestion_array, current_object);
}
var test_searchstring = 'Mar';
var test_current_object_string = '{"k":0,"y":0,"t":{"o":{"d":0}},"i":{"a":{"m":0}},"g":0}';
var test_current_object = JSON.parse(test_current_object_string);
console.log(test_current_object);
get_suggestion_array_from_object(test_searchstring, test_current_object);
function append_object_key(suggestion_array, current_object) {
var keys = Object.keys(current_object);
// CONCATENATE WITH SUGGESTION ARRAY ELEMENTS
var new_suggestion_array = [];
for (var i = 0; i < keys.length; i++) {
var current_key = keys[i];
var array_to_push = suggestion_array.slice();
for (var j = 0; j < suggestion_array.length; j++) {
array_to_push[j] = array_to_push[j] + current_key;
}
new_suggestion_array = new_suggestion_array.concat(array_to_push);
}
console.log(new_suggestion_array);
}
There are several approaches:
const get_suggestion_array_from_object = (searchstring, current_object_string) =>
current_object_string
.split(/[^a-z]+0[^a-z]+/)
.reduce((a, e) => e && a.concat(searchstring + e.replace(/[^a-z]+/g, '')) || a, [])
let searchstring = 'Mar';
let current_object_string = '{"k":0,"y":0,"t":{"o":{"d":0}},"i":{"a":{"m":0}},"g":0}';
console.log(get_suggestion_array_from_object(searchstring, current_object_string));
...
var test_searchstring = 'Mar';
var test_current_object_string = '{"k":0,"y":0,"t":{"o":{"d":0}},"i":{"a":{"m":0}},"g":0}';
var test_current_object = JSON.parse(test_current_object_string);
function get_suggestion_array_from_object(s, o) {
return Object.keys(o).map(function(k) {
var e = k;
var no = o[k];
while (no) {
var nk = Object.keys(no)[0];
e += nk;
no = no[nk];
}
return s + e;
})
}
console.log(get_suggestion_array_from_object(test_searchstring, test_current_object))

Why I split a specific array in a two-dimensional array but it also split another array as well

I have never faced this problem before and I really don't know how or why this can be occuring. Can anyone explain this for me?
There is also an image as well and it is on the top. As you can see in the picture, the last array didn't change while other arrays changed.
Here is the method (where I am facing my problem)
Object.prototype.createObject = function(name){
this[name] = [];
}
Array.prototype.matrixCreator = function(a3,b3){
var length = this.length;
if((this[1][0] && this[0][1]) === undefined){
var array1 = new Array(length-1);
for(var d3=0;d3<length-1;d3++){
array1[d3] = new Array(length-1);
}
}else{
var array = new Array(length);
for(var e3=0;e3<length;e3++){
array[e3] = new Array(length);
}
}
for(var c3=0;c3<length;c3++){
this[c3].splice(b3,1);
document.writeln(this[c3]);
if(c3 === a3){ // this prototype doesn't support the new design of matrix about spliting
if(c3===0){
this.splice(a3,1);
length--;
}else{
this.splice(a3,1);
c3--;
length--;
}
}
}
var f3;
var g3;
if((this[1][0] && this[0][1]) === undefined){
array1[0][0] = this[a][b];
for(var h3=1;h3<length;h3++){
for(var i3=1;i3<length;i3++){
array1[h3][i3] = this[h3][i3];
}
}
return array1;
}else{
array[0][0] = this[a3][b3];
for(var j3=1;j3<length+1;j3++){
for(var l3=1;l3<length+1;l3++){
f3 = j3-1;
g3 = l3-1;
array[j3][l3] = this[f3][g3];
}
}
return array;
}
}
// Here is the test code for my method:
var button = document.getElementById("button");
button.addEventListener("click",function(){
var array10 = new Array(4);
for(var b=0;b<4;b++){
array10[b] = [];
}
var array3 = [1,2,3,4];
var array4 = [5,6,7,8];
for(var c=0;c<4;c++){
array10[c]=array3;
array10[c+1]=array4;
}
var n = array10.length;
var controller = -1;
var key=0;var key1=0;
var obj ={};
var array=[]; var array1=[];
var flow=0;
while(key1 === 0){
for(var a=0;a<n;a++){
var string = "array" + a;
if(key==0){
obj.createObject(string);
array = array10.matrixCreator(0,a);
obj[string].push(array);
document.writeln(obj[string]);
}else{
for(var d=1;d<flow;d++){
array = obj[string][controller].matrixCreator(1,d);
obj[string].push(array);
document.writeln(obj[string]);
}
}
}
key=1;
controller++;
flow = obj[string][controller].length;
if(flow === 3){
break;
}
}
});
html code:
<input type="button" id="button" value="press here"/>

backtracking in javascript, can't update global variable

I'm trying to solve problem of day 9 of the advent of code in javascript.
I'm using backtracking for getting all possible routes and then calculate the cost of each one.
I'm used to do backtracking in languages like PHP and C++, but never did in JS, so I've found thanks to google that you can't pass a mutable parameter like the & parameters in both PHP and C++.
My intent is to assign the bestRoute variable to the best route because that is the solution of the problem.
But when I do that, using return in some sites, I get an undefined variable error like this:
for (var i = 0 ; i < neighborsArray.length ; i++) {
^
TypeError: Cannot read property 'length' of undefined at getCostInNeighbors (/home/freinn/librosjavascript/advent_of_code/day9.js:117:40)
at calculateCost (/home/freinn/librosjavascript/advent_of_code/day9.js:110:17)
Here is my current code, that does not work and prints bestRoute like the first defined.
"use strict";
function clone(obj) {
// Handle the 3 simple types, and null or undefined
if (null == obj || "object" != typeof obj) return obj;
// Handle Date
if (obj instanceof Date) {
var copy = new Date();
copy.setTime(obj.getTime());
return copy;
}
// Handle Array
if (obj instanceof Array) {
var copy = [];
for (var i = 0, len = obj.length; i < len; i++) {
copy[i] = clone(obj[i]);
}
return copy;
}
// Handle Object
if (obj instanceof Object) {
var copy = {};
for (var attr in obj) {
if (obj.hasOwnProperty(attr)) {
copy[attr] = clone(obj[attr]);
}
}
return copy;
}
throw new Error("Unable to copy obj! Its type isn't supported.");
}
function generateGraphAsArray(input) {
var lines = input.split("\n");
var getFromTo = /(.*?) to (.*?) = (\d+)/;
var graph = {};
var matches = [];
for (var i = 0 ; i < lines.length ; i++) {
matches = getFromTo.exec(lines[i]);
// console.log(matches[1], matches[2], matches[3]);
var obj = {};
obj['to'] = matches[2];
obj['cost'] = matches[3];
var clonated = clone(obj);
if (!(matches[1] in graph)) {
graph[matches[1]] = [];
}
graph[matches[1]].push(clonated);
if (!(matches[2] in graph)) {
graph[matches[2]] = [];
}
obj['to'] = matches[1];
clonated = clone(obj);
graph[matches[2]].push(clonated);
}
var keys = Object.keys(graph);
var graphArray = [];
var nodeList;
// recuerda: en JS la funcion que no devuelve nada, devuelve algo, undefined
// si no ponemos return en la funcion del map, dara undefined
for (var prop in graph) {
// esto es una clausura sana para poder usar keys
nodeList = graph[prop].map(function(obj) {
return nodeObjectToArray(keys, obj);
});
graphArray.push(nodeList);
}
return graphArray;
}
function nodeObjectToArray(keys, obj) {
var array = new Array(keys.indexOf(obj.to), Number(obj.cost));
return array;
}
function generateAllRoutes(numberOfNodes, graphArray) {
var routes = [];
for (var i = 0 ; i < numberOfNodes; i++) {
var array = [i]
routes.push(array);
}
var bestRoute = generateRangeWithoutUsed([], numberOfNodes);
for (var i = 0 ; i < routes.length; i++) {
bestRoute = generateRoutes(routes[i], numberOfNodes, bestRoute, graphArray);
}
console.log(bestRoute, calculateCost(bestRoute, graphArray));
}
function calculateCost(route, graphArray) {
var limit = graphArray.length - 1;
var cost = 0;
for (var i = 0 ; i < limit ; i++) {
cost += getCostInNeighbors(graphArray[route[i]], route[i+1]);
}
return cost;
}
function getCostInNeighbors(neighborsArray, neighbour) {
for (var i = 0 ; i < neighborsArray.length ; i++) {
if (neighborsArray[i][0] == neighbour) {
return neighborsArray[i][1];
}
}
}
function generateRoutes(currentRoute, numberOfNodes, bestRoute, graphArray) {
if (currentRoute.length == numberOfNodes) {
var currentRouteCost = calculateCost(currentRoute, graphArray);
console.log(currentRouteCost);
if (currentRouteCost < calculateCost(bestRoute, graphArray)) {
return currentRoute;
} else {
return bestRoute;
}
} else {
var possibleNextNodes = generateRangeWithoutUsed(currentRoute, numberOfNodes);
for (var i = 0 ; i < possibleNextNodes.length ; i++) {
currentRoute.push(possibleNextNodes[i]);
generateRoutes(currentRoute, numberOfNodes, bestRoute, graphArray);
currentRoute.splice(-1, 1); // remove the last element
}
}
}
function generateRangeWithoutUsed(used, numberOfNodes) {
var rangeWithoutUsed = [];
for (var i = 0 ; i < numberOfNodes ; i++) {
if (!existInArray(i, used)) {
rangeWithoutUsed.push(i);
}
}
return rangeWithoutUsed;
}
function existInArray(element, array) {
for (var i = 0 ; i < array.length ; i++) {
if (array[i] == element) {
return true;
}
}
return false;
}
var input = "Faerun to Norrath = 129\nFaerun to Tristram = 58\nFaerun to AlphaCentauri = 13\nFaerun to Arbre = 24\nFaerun to Snowdin = 60\nFaerun to Tambi = 71\nFaerun to Straylight = 67\nNorrath to Tristram = 142\nNorrath to AlphaCentauri = 15\nNorrath to Arbre = 135\nNorrath to Snowdin = 75\nNorrath to Tambi = 82\nNorrath to Straylight = 54\nTristram to AlphaCentauri = 118\nTristram to Arbre = 122\nTristram to Snowdin = 103\nTristram to Tambi = 49\nTristram to Straylight = 97\nAlphaCentauri to Arbre = 116\nAlphaCentauri to Snowdin = 12\nAlphaCentauri to Tambi = 18\nAlphaCentauri to Straylight = 91\nArbre to Snowdin = 129\nArbre to Tambi = 53\nArbre to Straylight = 40\nSnowdin to Tambi = 15\nSnowdin to Straylight = 99\nTambi to Straylight = 70";
// var myInput = "a to b = 1\na to c = 2\nb to d = 7\nc to d = 1\nc to e = 3\nd to f = 2\ne to f = 5";
var graphArray = generateGraphAsArray(input);
generateAllRoutes(graphArray.length, graphArray);
In generateRoutes, if your else case happens, the function returns null (because there is no return statement), wicht sets bestRoute to null, wich causes an error the next time calculateCost gets called

An alternative method for JSON.stringify()

I want an alternative method for JSON.stringify().
I am using JSON.stringify and I got error like cyclic object value. I don't know how to remove this error so I'd like to know if there's an alternative method.
DCSSPACE.SaveAndOpenJSONWriter = function(canvas) {
//multiple tab.....
var mydata = [];
var area = {}, DCS = {}, workspace = {};
var len = DCSSPACE.collection.length;
for (var k = 0; k < len; k++) {
var result = [];
var tabid = DCSSPACE.collection.models[k].id;
var canvas = DCSSPACE.collection.get(tabid).get("workflow");
//for node
var figures = canvas.getFigures();
for (var i = 0; i < figures.getSize(); i++) {
if (figures.get(i).type == "draw2d.Node") {
var node = {};
node.blockType = getBlockType(figures.get(i));
node.x = figures.get(i).getX();
node.y = figures.get(i).getY();
node.id = figures.get(i).getId();
node.type = figures.get(i).type;
node.width = figures.get(i).getWidth();
node.height = figures.get(i).getHeight();
node.label = figures.get(i).getLabel();
node.sequenceNo = figures.get(i).getSequenceNo();
node.model = figures.get(i).model;
result.push(node);
}
}
//for lines
var lines = canvas.getLines();
for (var j = 0; j < lines.getSize(); j++) {
if (lines.get(j).type == "draw2d.nodeConnetion") {
var nodeConnection = lines.get(j).getConnectionAttrubutes();
nodeConnection.source = lines.get(j).getSource();
nodeConnection.target = lines.get(j).getTarget();
result.push(nodeConnection);
}
}
area = {
tabid : tabid,
attr : result
};
mydata.push(area);
result=[];
workspace = {
DCS : mydata
};
}
//console.log(mydata);
var arr = JSON.stringify(workspace, null, 4);
console.log(arr);
DCSSPACE.SaveAndLoadFigure = result;
return workspace;
};
If won't to use stringify you can reproduce it, like this:
OBJtoString(object [,n]) accempt 2 args:
object (needed) the object you need to log (in my release array and object is the same)
n numbero of space that indent every new line inside object aruments.
var OBJtoString = function(_o,_m,_rf,_dep,_res){
_dep = [],
_rf = function(obj,n,_n,_a,_k,_i,_ws,_f,_e){
if(typeof obj != "object") return false;
if(typeof _a === "undefined") _a = "FIRST PARENT OBJECT";
_dep.push(obj),
_f = (_dep.length < 1) ? function(){} : function(_z,_x){
for(_x = 0; _x <= _dep.length; _x++){
if(obj[_z] == _dep[_x]) return true;
}
return false;
}
_ws = "";
if(typeof n === "undefined") n = 1;
if(typeof _n === "undefined") _n = n;
for(_k = 0; _k <= n; _k++){
_ws += " ";
}
var response ="{ \n";
for(var _i in obj){
if(typeof obj[_i] !== "object"){
if(typeof obj[_i] === "string") obj[_i] = "'"+obj[_i].toString()+"'";
if(typeof obj[_i] === "boolean") obj[_i] = obj[_i].toString() + " (boolean)";
response += _ws + _i + " : " + obj[_i].toString();
response += "\n";
continue;
}
response += (_f(_i)) ? _ws + _i + " : "+ _a +" (prevent loop)\n" : _ws + _i + " : " + _rf(obj[_i],n+_n,_n,_a);
}
if(_n != n) response += _ws;
return response +="} \n";
}
_res = _rf(_o,_m);
_dep = [];
return _res;
}
Uses Example:
var example = {ciao : "hellow", saluto : {ciao : "ciao", dam : true}};
example.parentObj = example;
console.log(OBJtoString(example,4));
return:
{
ciao : 'hellow'
saluto : {
ciao : 'ciao'
dam : true (boolean)
}
parentObj : FIRST PARENT OBJECT (prevent loop)
}
Other Example:
var example = {ciao : "hellow", saluto : {ciao : "ciao", dam : true}};
example.parentObj = example;
example.f = {
g : example
}
console.log(OBJtoString(example,4));
Return:
{
ciao : 'hellow'
saluto : {
ciao : 'ciao'
dam : true (boolean)
}
parentObj : FIRST PARENT OBJECT (prevent loop)
f : {
g : FIRST PARENT OBJECT (prevent loop)
}
}
I found util.inspect() pretty helpful.
You can print entire object
console.log(util.inspect(myObj))
Or with optional arguments
util.inspect(object, showHidden=false, depth=2, colorize=true)
Documentation:
https://nodejs.org/en/knowledge/getting-started/how-to-use-util-inspect/

How to parse input[] values and put them into a Javascript Array

Let's say i have this:
<form id='foo'>
<input name='bar[name]' />
<input name='bar[age]' />
</form>
How can i get the values of array inputs within the form foo and put them into an associative array/object like this:
var result = {bar:{name:'blah',age:21}};
P.S. I don't want to use any frameworks for this.
I needed to do this myself and after finding this question I didn't like any of the answers: I don't like regex and the others are limited.
You can get the data variable many ways. I'll be using jQuery's serializeArray method when I implement this.
function parseInputs(data) {
var ret = {};
retloop:
for (var input in data) {
var val = data[input];
var parts = input.split('[');
var last = ret;
for (var i in parts) {
var part = parts[i];
if (part.substr(-1) == ']') {
part = part.substr(0, part.length - 1);
}
if (i == parts.length - 1) {
last[part] = val;
continue retloop;
} else if (!last.hasOwnProperty(part)) {
last[part] = {};
}
last = last[part];
}
}
return ret;
}
var data = {
"nom": "123",
"items[install][item_id_4]": "4",
"items[install][item_id_5]": "16",
"items[options][takeover]": "yes"
};
var out = parseInputs(data);
console.log('\n***Moment of truth:\n');
console.log(out);
You can map the elements to an object like this.
function putIntoAssociativeArray() {
var
form = document.getElementById("foo"),
inputs = form.getElementsByTagName("input"),
input,
result = {};
for (var idx = 0; idx < inputs.length; ++idx) {
input = inputs[idx];
if (input.type == "text") {
result[input.name] = input.value;
}
}
return result;
}
var form = document.getElementById( 'foo' );
var inputs = form.getElementsByTagName( "input" );
var regex = /(.+?)\[(.+?)\]/;
var result = {};
for( var i = 0; i < inputs.length; ++i ) {
var res = regex.exec( inputs[i].name );
if( res !== null ) {
if( typeof result[ res[1] ] == 'undefined' ) result[ res[1] ] = {};
result[ res[1] ][ res[2] ] = inputs[i].value;
}
}
var inputs = document.getElementsByTagName('input');
var field_name, value, matches, result = {};
for (var i = 0; i < inputs.length; i++) {
field_name = inputs[i].name;
value = inputs[i].value;
matches = field_name.match(/(.*?)\[(.*)\]/);
if (!results[matches[0]]) {
results[matches[0]] = {};
}
results[matches[0]][matches[1]] = value;
}
This will get you the elements:
var result = {};
var elements = document.forms.foo.getElementsByTagName("input");
for(var i = 0; i < elements.length; i++)
{
/* do whatever you need to do with each input */
}

Categories

Resources