how to search through object data? [duplicate] - javascript

This question already has answers here:
How do I enumerate the properties of a JavaScript object? [duplicate]
(14 answers)
Closed 8 years ago.
I have multiple objects with x and y values,
var object = new Object();
object.one = new Object();
object.one.x = 0;
object.one.y = 0;
object.two = new Object();
object.two.x = 1;
object.two.y = 1;
How would you determine which object has an x and a y that = 1?
You could pass is an x and y value to a function.
function = function(x,y) {
// code to find which objects x and y = parameters
};

Maybe "x in y" loop is what you are looking for. Here is how you do it:
for(var p in object) // String p will be "one", "two", ... all the properties
{
if(object[p].x == 1 && object[p].y == 1) console.log(p);
}
Here is more info http://www.ecma-international.org/ecma-262/5.1/#sec-12.6.4 .

I'd use something along the lines of:
var findObject = function(object, x, y) {
for(var subObject in object) {
if(object[subObject].x === x && object[subObject].y === y)
return object[subObject];
}
};
Then using findObject(object, 1, 1) will give you the object with x and y equal to 1.
See this fiddle.

search = function(x, y) {
for (var p in object) {
if (object[p].x == x && object[p].y == y) console.log(p);
}
}
search(1, 1)
Should work just fine, but you should probably make the function have a variable 'object' so rather than this hardcoded example.

Related

array changing values for a strange reason

Given the code below:
function createJson() {
var varry = new Array();
varry = x;
for (i=0 ; i < arry.length ; i++) {
if (arry[i]["questionVisibility"] == "1"){
if (arry[i]["questionType"] != 3) {
varry[i][1] = document.getElementById('te'+arry[i]["id"]+'et').value;
} else {
e = document.getElementsByName("te"+arry[i]["id"]+"et")[0];
p = e.options[e.selectedIndex];
varry[i][1] = p.text;
}
}
}
console.log(x);
console.log(varry);
Where X is an array that has been created like this(inside a different function):
x = document.getElementById("jsonData").value;
x = JSON.parse(x);
x = x[0];
x = x.data;
x = JSON.parse(x);
Can anyone explain me why when i call the createJson() function, the x array is changed? (x is already created when the createJson() is called)
Thanks in advance!
it's because of line
varry = x;
assigning an array to variable creates kind of reference of original value so when you modify varry it also modifies x
if you want to get a copy of x into varry without reference use
array.slice() like this:
varry = x.slice();
this will insert values from x into varry without creating 'reference' to original array

What is the difference between using 'this' keyword and var in a constructor function in JavaScript? [duplicate]

This question already has answers here:
javascript var vs this [duplicate]
(4 answers)
Closed 5 years ago.
I'm learning object concepts in JavaScript and have this doubt. Here is the link to the Bin http://jsbin.com/yoyepetewa/edit?js,console
function Obj() {
//using 'this' and var produces the same result
//this.x = 1;
var x = 1;
}
var a = new Obj();
var b = new Obj();
a.x = 2;
b.x = 3;
console.log(`a's x = ${a.x}`);
console.log(`b's x = ${b.x}`);
using 'this' and var produces the same result
No, it doesn't. var x = 1; does absolutely nothing in terms of setting a property on the object.
But since you're adding an x property later, you're not seeing that it doesn't do the same thing. If we look at x before you set it to 2 or 3, we can see the difference.
Compare using this:
function Obj() {
this.x = 1;
//var x = 1;
}
var a = new Obj();
console.log(`(1) a's x = ${a.x}`);
var b = new Obj();
console.log(`(1) b's x = ${b.x}`);
a.x = 2;
b.x = 3;
console.log(`(2) a's x = ${a.x}`);
console.log(`(2) b's x = ${b.x}`);
...to using var:
function Obj() {
//this.x = 1;
var x = 1;
}
var a = new Obj();
console.log(`(1) a's x = ${a.x}`);
var b = new Obj();
console.log(`(1) b's x = ${b.x}`);
a.x = 2;
b.x = 3;
console.log(`(2) a's x = ${a.x}`);
console.log(`(2) b's x = ${b.x}`);
Notice how x starts out undefined.

Fast way to check the biggest variable? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 7 years ago.
Improve this question
I need a way to get the name of the variable with the greatest value.
a = 55;
b = 13;
c = 45;
d = 5;
var top = '';
if((a>b)&&(a>c)&&(a>d)){ top = 'a'; }
if((b>a)&&(b>c)&&(b>d)){ top = 'b'; }
if((c>a)&&(c>b)&&(c>d)){ top = 'c'; }
if((d>a)&&(d>b)&&(d>c)){ top = 'd'; }
Is there a better or faster way to do this?
You can't get the variable name directly:
Very few languages support what you want to do because the variable
names only exist for your benefit in the source code. They do not
exist in the compiled executable code in that form anymore and
tracking them would be extremely expensive.
If you want to do this, there is something fundamentally wrong with your design as there is no reason that would preclude doing it the most idiomatic way possible which is to use an associative array, which in JavaScript means using an Object or an actual Map when available and where appropriate.
Object based approach:
Most compatible way if you do not have access to Map:
You can use an object and find the property name. The most concise way to do this is with the Array.reduce() function.
var obj = {a:55,b:13,c:45,d:5};
var maxPropertyName = Object.keys(obj).reduce(function(previous,key){
return obj[previous] > obj[key] ? previous : key;
})
console.log(maxPropertyName);
Output:
a
Map based approach:
For this case a Map seems more appropriate since this looks like a homogeneousCollection rather than a Type of something.
Map instances are only useful for collections, and
you should consider adapting your code where you have previously used
objects for such. Objects shall be used as records, with fields and
methods. If you're still not sure which one to use, ask yourself the
following questions:
Are keys usually unknown until run time, do you need to look them
up dynamically?
Do all values have the same type, and can be used interchangeably?
Do you need keys that aren't strings?
Are key-value pairs often added or removed? Do you have an
arbitrary (easily changing) amount of key-value pairs?
Is the collection iterated? Those all are signs that you want a Map
for a collection.
If in contrast you have a fixed amount of keys, operate on them
individually, and distinguish between their usage, then you want an
object.
Here is how to add a .reduce() method to Map:
Map.prototype.reduce = function(callback){
'use strict';
if (this == null) {
throw new TypeError('Array.prototype.reduce called on null or undefined');
}
if (typeof callback !== 'function') {
throw new TypeError(callback + ' is not a function');
}
var t = Object(this), value;
if (t.size === 0) { value = undefined; }
else if (t.size === 1) { value = t.keys().next().value; }
else {
value = t.keys().next().value;
for (var kv of t) {
value = callback(value, kv[0]);
}
}
return value;
};
Same .reduce() code now works:
var m = new Map([["a",55],["b",13], ["c",45],["d",5]]);
var maxPropertyName = m.reduce(function(previous,key){
return m.get(previous) > m.get(key) ? previous : key;
})
console.log(maxPropertyName);
Output:
a
A simple way to do it, store everything in an object and loop over the keys:
// you can keep the input variables
var a = 55;
var b = 13;
var c = 45;
var d = 5;
var obj = {
a: a,
b: b,
c: c,
d: d
}
var max;
var varName;
Object.keys(obj).forEach(function(key) {
if (!max || max < obj[key]) {
max = obj[key];
varName = key;
}
});
snippet.log(max);
snippet.log(varName);
<script src="https://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
function high(obj) {
var highest = Number.NEGATIVE_INFINITY,
keyName = null;
for (var key in obj) {
if( obj[key] > highest ) {
highest = obj[key];
keyName = key;
}
}
return keyName;
}
In this way you can need not care about the variable name.Also need not repeat the variable name.
// init
var obj={};
var max=0,maxName="";
var x={};
for(var key in window){
x[key]=window[key];
}
// your code
a = 55;
b = 13;
c = 45;
d = 5;
// end of your code
// select the max num
for(var key in window){
if(typeof(window[key]) == "number" && typeof(x[key])!="number"){
if(window[key]>max){
max=window[key];
maxName=key;
}
}
}
// output the variable name
console.log(maxName);
And you can write a method to reuse:
function getTop(func){
// init
var obj={};
var max=0,maxName="";
var x={};
for(var key in window){
x[key]=window[key];
}
func();
// select the max num
for(var key in window){
if(typeof(window[key]) == "number" && typeof(x[key])!="number"){
if(window[key]>max){
max=window[key];
window[key]=undefined;
maxName=key;
}
}
}
// output the variable name
return maxName;
}
you can use the code to get the top varname:
var top=getTop(function(){
a=11;
b=22;
c=23;
d=14;
});
One way, if you cannot use object, then get max value and then check individual values to variable. Here you will not have very complex condition. Also its better to if...else if...else than multiple if
a = 55;
b = 13;
c = 45;
d = 5;
var max = Math.max(a,b,c,d);
var varName = "";
if(max === a){
varName = "a";
}
else if(max === b){
varName = "b";
}
else if(max === c){
varName = "c";
}
else{
varName = d;
}
alert(varName);

Swapping Two Values in an Array [duplicate]

This question already has answers here:
Javascript swap array elements
(33 answers)
Closed 9 years ago.
I'm having trouble in figuring out what JavaScript code would work in swapping two values (numbers in this case) in an array.
The function (referred to as move) will swap the position of the value that you clicked with the position of "". The array values are displayed on the page and the function initiates when you click on any number (via onclick).
boxArray = ["1","2","3","4","5","6","7","8","9","10","11","12","13","14","15",""]
function move() {
}
To swap two values, use some logic, store one value in a temporary variable, set the first to the second, and the second to the temporary variable :
function swap(array, index1, index2) {
var temp = array[index1];
array[index1] = array[index2];
array[index2] = temp;
}
It's really that easy
FIDDLE
Maybe this (here's the jsfiddle):
<button>1</button><button>2</button>
$('button').click(function() {
var val = $(this).html();
swap(val);
});
var boxArray = ["1","2","3","4","5","6","7","8","9","10","11","12","13","14","15",""]
function swap(el) {
var blankIndex = boxArray.indexOf(""),
elIndex = boxArray.indexOf(el);
boxArray[blankIndex] = el;
boxArray[elIndex] = "";
console.log(boxArray);
}
I can't tell precisely what you're trying to do, but I believe I get the gist of it. array.splice is the function you're likely looking for:
function move(arr, from, to) {
if (from >= arr.length || to >= arr.length) return;
var y = arr.splice(from, 1)[0];
arr.splice(to, 0, y);
}
var x = [1,2,3];
move(x, 0, 2); // moves the value at position 0 to position 2: [2,3,1]

How do i sort my javascript objects when taking them from an array? [duplicate]

This question already has answers here:
Sort array of objects by string property value
(57 answers)
Closed 9 years ago.
I have a big array containing 52 objects, each representing a specific card in a deck of cards.
var deck = [{'suit': 's', 'value' : A}, {'suit': 'h', 'value' : 9}...]
srepresenting the spade suit, and A for the Ace of spades in this case, and so on.
I have managed (thanks to some guidance from friendly souls here on stackoverflow) to randomize this deck, added 13 of these to a player, and got those to show in an <ul>on my page.
My problem is, that the values form the deck array i add to the player, i am adding as it is, meaning, the output could be:
♠89A, ♥A29J, ♦KTJ37, ♣8
Which is not optimal.
I would like to be able to sort the cards from A to 2, e.g. ♠AJ72, ♥JT92.. and so on.
Since the deck array will take a huge amount of space, i'm deleteing it from the code i show here. But here is the whole code: Liveweave (pretty sweet codeapp i must say)
This is my javascript:
var deal = function () {
//Player hands
var north_hand = [];
var east_hand = [];
var south_hand = [];
var west_hand = [];
//Creating the deck
var deck = [{'suit': 's', 'value': 'A'}, ... //+51 more cards];
//Call the shuffleDeck function
shuffleDeck(deck);
north_hand = deck.slice(0, 13);
east_hand = deck.slice(13, 26);
south_hand = deck.slice(26, 39);
west_hand = deck.slice(39, 52);
var north_spades = document.getElementById('p1_spades');
var north_hearts = document.getElementById('p1_hearts');
var north_diamonds = document.getElementById('p1_diamonds');
var north_clubs = document.getElementById('p1_clubs');
for (var i = 0; i < north_hand.length; i++) {
if (north_hand[i].suit == "s") {
north_spades.innerHTML += north_hand[i].value;
} else if (north_hand[i].suit == "h") {
north_hearts.innerHTML += north_hand[i].value;
} else if (north_hand[i].suit == "d") {
north_diamonds.innerHTML += north_hand[i].value;
} else {
north_clubs.innerHTML += north_hand[i].value;
}
}
}
You have to write a custom comparator function and pass it to the sort function of your hand array.
hand.sort(function(a,b) {
var values = {A:13,K:12,Q:11,J:10};
var c = a.value;
var d = b.value;
if(c.match(/[A-Z]/) != null) {
c = values[c];
}
if(d.match(/[A-Z]/) != null) {
d = values[d];
}
return d-c;
});

Categories

Resources