How to check for value in javascript object? [duplicate] - javascript

This question already has answers here:
How to get a key in a JavaScript object by its value?
(31 answers)
Closed 7 years ago.
I do have a javscript object containing a product name and the corresponding product code. The code is unique.
var products = {
"Pineapple":38,
"Apple":110,
"Pear":109
};
If i want to know the code for a product i can just do
var pineapplecode = products["Pineapple"];
How do I check if there is a product for a given number and if print it ? Or do I have to/should I change the way the data is saved ?

I think the shortest way would be:
var prodCode = 38;
var result = Object.keys(products)
.filter(function(k) { return products[k] == prodCode; })[0];
// result == "Pineapple"
See MDN

I guess you are basically asking if I can check the other way round, i.e. check for key by passing value.
Yes you can,
Either by iterating through all the key and values, check if the value is existing and finally return the key if the value exists
change the way you save the data, index it by product number rather than product name
here is the code to convert one form to another
var newProducts = {};
for( var prodName in products )
{
newProducts[ products[ prodName ] ] = prodName;
}
console.log( newProducts );
And here is the code to check a specific value
var valueToCheck = "110";
var prodNameToFind = "";
for( var prodName in products )
{
if ( products[ prodName ] == valueToCheck )
{
prodNameToFind = prodName;
}
}
console.log( prodNameToFind );

Just iterate over the keys and the properties values and break the iteration if found with Array.prototype.some()
The some() method tests whether some element in the array passes the test implemented by the provided function.
var products = {
Pineapple: 38,
Apple: 110,
Pear: 109
};
function getProduct(code) {
var product;
Object.keys(products).some(function (k) {
if (products[k] === code) {
product = k;
return true;
}
});
return product;
}
document.write(getProduct(109));

Related

Find if values exists in an array of object (Angularjs) [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am having a hard time trying to get this right. I would be glad if someone could help me get a solution for this.
0: Object
Name: Ria
Age: 27
Sex: Female
1: Object
Name: Brian
Age: 23
Sex: Male
2: Object
Name: Rick
Age: 32
Sex: Male
Here is the array of objects. I am passing a user entered value. for e.g. I ask the user to enter the name. Once entered, i need to check in the above array of objects, if the Name is present in the array of objects.
I tried a variety of solutions using foreach, basic array itereation and i couldnot find a way.
Here is what i tried at the last...
var result = false;
function search(nameKey, myArray) {
for (var i = 0; i < myArray.length; i++) {
if (myArray[i].Name === nameKey) {
return true;
}
}
}
result = search($scope.data.name, checkdatabase);
Here, checkdatabase is the array of objects and $scope.data.name is the user entered value. I am expecting the value of result as true when user is present in database or else result as false which is defined initially.
What you need is Array.prototype.some:
result = myArray.some(function(user) { return user.name === $scope.data.name; });
BTW, this is just a suggestion: I would store an index of user names and use Array.prototype.indexOf.
Whenever you add an user, you can add the name to an array:
var userNameIndex = [];
var users = [];
users.push(user);
// I've called .toLowerCase() so the index isn't case sensitive
userNameIndex.push(user.Name.toLowerCase().trim());
...and you can check if the user has been already added as follows:
// I've called .toLowerCase() to perform a case insensitive search
var result = userNameIndex.indexOf($scope.data.name.toLowerCase().trim()) > -1;
It should perform better if you're retrieving a lot of users.
I am expecting the value of result as true when user is present in
database or else result as false which is defined initially.
Yes, but note that calling search sets the variable result again. That is, the initial false is never preserved.
To extend Matias' answer, some is great for the job as long as you don't need the item that matches your predicate. some accepts a context as a second argument:
result = myArray.some(function(user) {
return user.name === this.name;
}, $scope.data); //pass $scope.data as this
If your want to keep track of the item that matches the predicates, you have several options: Create an object of indexes or iterate over the array using forEach or while
var index = myArray.map(function(item) {
return item.name;
}).indexOf(nameKey);
var item = myArray[index];
var l = myArray.length;
var found = false;
while(!found && l--) {
found = myArray[l].name === nameKey;
}
var item = myArray[l];
use lodash.js. you can filter the array with given parameter.
For Example :
var givenJson ={ Name: Ria,Age: 27,Sex: Female};// this is the whole array
var response= _.filter(givenJson, function(data){
return data.name == "Ria";
});
if(response != null && response != undefined){
return true;
}

How to remove items from array who's got the same values [duplicate]

This question already has answers here:
How to remove all duplicates from an array of objects?
(77 answers)
Closed 7 years ago.
I am making some checking between array. It is in NodeJS.
The question is:
I have an array:
var items = [];
than I insert some values into it:
items[0] = {a:1, b:222};
items[1] = {a:1, b:333};
items[2] = {a:1, b:222};
items[3] = {a:1, b:4444};
items[4] = {a:1, b:222};
So, what I need to do is: to go threw all array and remove item's that has the same 'b' value.
Example:
After filtering, it should look like:
items[0] = {a:1, b:222};
items[1] = {a:1, b:333};
items[2] = {a:1, b:4444};
As you see elements with indexes 2 and 4 gone, because they has the same b value as element at index 0.
How can I write this little code in JavaScript?
You're looking for an Array.prototype.filter function:
var bValues = {};
items = items
.filter(function(item) {
return bValues[item.b] === undefined && (bValues[item.b] = true);
});
This works by checking if we have seen a particular bValue, and returning false if we have. If we haven't, we set that value on the bValues map and return true.
Edit: I like the nifty suggestion of #dandavis, using the this binding parameter to reduce variable names:
items = items
.filter(function(item) {
return this[item.b] === undefined && (this[item.b] = true);
}, {});
If I understand your question correctly, you want to do a pass to remove every single duplicate b value. This is actually more of an algorithm question than a Javascript question. There are lot of ways to do this, but my answer is going to focus on performance.
Here is one of the faster ways to do this in Javascript (O(n)):
var items = [];
// Insert a bunch of items with signature {a: Number, b: Number}
items = removeDuplicatesOfB(items);
function removeDuplicatesOfB(items) {
var map = {};
var filtered = [];
items.forEach(function (item) {
if (!map[item.b]) {
filtered.push(item);
map[item.b] = true;
}
});
return filtered;
}
At this point you could focus on abstracting out the duplicate removal to make this a reusable function.
All the answers propose roughly equivalent algorithms, so it boils down to what is most understandable. Here's one idea. We'll start off by describing the algorithm in English:
Of all the items, keep those with the first b.
For an item, "first b" means the index of this item is equal to the index of the first element whose b property is equal to the b property of the item.
Now we can pretty much transform that English into JavaScript.
function removeDuplicatesOfB(items) {
// Is this item the first in the array with its b property?
function firstB(item, idx) {
return idx // The index of this item
=== // equal to
items.findIndex( // the index of the first
e => // element
e.b // whose b property
=== // is equal to
item.b // the b property of the item.
)
;
}
return items . // Of all the items,
filter( // keep those with
firstB // the first b.
)
;
}
Or, in non-commented form:
function removeDuplicatesOfB(items) {
function firstB(item, idx) {
return idx === items.findIndex(e => e.b === item.b);
}
return items.filter(firstB);
}
Underscore
Underscore's _.uniq can do this in its sleep, by passing it a "predicate" telling it how to compare the objects for purposes of determining whether they are the "same":
_.uniq(items, function(item) { return item.b; })

Javascript number of object by different property values in array

Best way to count the number of objects in a array with different object property p values.
function([{"p":"a"},{"p":"b"},{"p":"a"}]){
// some code
}
// in this case return 2
You can use Array.prototype.filter() to keep values that you want. In this case, you must create a variable temp for storing duplicate values and also within the filter function returns true if it does not exist in case. So you have a new array of unique values.
var arr = [{"p":"a"},{"p":"b"},{"p":"a"}], temp = [];
var arrUniques = arr.filter(function(obj){
return temp.indexOf(obj.p) === -1 ? !!temp.push(obj.p) : false
});
alert(arrUniques.length)
With a Map:
var props = new Map();
for (var i = 0; i < array.length; i++) {
var prop = array[i].p,
count = props.get(prop) || 0;
props.set(prop, count + 1);
}
var size = props.size;
If your properties can be safely casted to strings, you can use a common object:
var props = {};
...
var size = Object.keys(props).length;
Otherwise, Map is your answer.
function getUniquePropertyCount(a, p) {
return a.reduce(function (res, el) {
!~res.indexOf(el[p]) && res.push(el[p]);
return res;
}, []).length;
}
document.write(getUniquePropertyCount([{ "p": "a" }, { "p": "b" }, { "p": "a" }], 'p'));
I suppose this is one of those questions where if you ask four programmers, you'll get five answers.
The other answers so far show some interesting approaches. I would watch out for browser compatibility; for example Map() is only available in the newest browsers, not in IE 10 or prior.
So here's one more solution. It's a bit more code, but it's pretty easy to understand, and it works in every browser:
function countUniqueProperties( key, array ) {
var count = 0, values = {};
for( var i = 0; i < array.length; ++i ) {
var value = array[i][key];
if( ! Object.prototype.hasOwnProperty.call( values, value) ) {
++count;
values[value] = true;
}
}
return count;
}
countUniqueProperties( 'p', [ {p:'a'}, {p:'b'}, {p:'a'} ] );
The one complicated part here is the Object.prototype.hasOwnProperty.call(values,value). You could just use values.hasOwnProperty(value), but that would fail if one of your property values was the string "hasOwnProperty":
countUniqueProperties( 'p', [ {p:'a'}, {p:'hasOwnProperty'}, {p:'a'} ] );
Using the longer form avoids this issue.
lodash is nice for things like this.
Use
_.uniq([{"p":"a"},{"p":"b"},{"p":"a"}]).length
and it'll return 2.

Filtering a JavaScript array [duplicate]

This question already has an answer here:
How to filter a javascript object array with variable parameters
(1 answer)
Closed 9 years ago.
I am looking for a way to filter my JavaScript Array() columns where the parentId is equal to a variable passed into the method.
// Array decleration
var columns = []; // Columns
//...
for (var i1 in columns) {
if (columns[i1].parentId == listItem) {
//...
Could anybody recommend the easiest way to filter this using either plain JavaScript or jQuery to avoid using the if statement as shown above?
var filteredColumns = columns.filter(function(column) {
return column.parentId == listItem;
});
array = [1,2,3,4,5];
result = $.grep(array, function(n,i) {
return n > 3;
});
This will return an array of filtered elements where the results are greater than 3. Here n is the element in consideration, and i the index of the element. So as per your requirement, the code can run like this:
resultArray = $.grep(columns,function(n,i) {
return n == parentId;
});
Use ES5 Array's filter method:
var filtered = columns.filter(function (item) {
return item.parentId === listItem
});
In the link above there is also a shim for old browsers.
You can also doing that manually:
var filtered = [];
for (var i = 0, item; item = columns[i++];)
if (item.parentId === listItem) filtered.push(item);
Don't use for…in to iterate over Array.

pick random value from associated array using javascript? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicates:
JavaScript: Getting random value from an array
How can I choose an object key at random?
suppose we have an array like this:
var MrArray = new Array(5);
MrArray['one']='oneValue';
MrArray['two']='twoValue';
MrArray['three']='threeValue';
MrArray['four']='fourValue';
MrArray['five']='fiveValue';
ok?
the Array is associated.
and we have string key and string value.
now! how can i pick a random value from that?
Edit:i want to use like this:
Array Key Here
Regards
Sam
Using the method described here we can create the following function:
function randomKey(obj) {
var ret;
var c = 0;
for (var key in obj)
if (Math.random() < 1/++c)
ret = key;
return ret;
}
It returns a random key, so to get a random value from MrArray, do this:
var value = MrArray[randomKey(MrArray)];
jsPerf benchmark comparing the speed of this and the other answer.
Here:
function fetch_random(obj) {
var temp_key, keys = [];
for(temp_key in obj) {
if(obj.hasOwnProperty(temp_key)) {
keys.push(temp_key);
}
}
return obj[keys[Math.floor(Math.random() * keys.length)]];
}
Src: How can I choose an object key at random?

Categories

Resources