Get length of same key in array of javascript objects - javascript

var arr = [{code:'A', number: 1}, {code:'A', number: 2}, {code:'B', number: 3 }]
How can I get a number of objects that has certain key in above array?
For example, The number of code: 'A' objects is 2.
How to get it?

filter will iterate through the array and execute your callback function. The callback function needs to evaluate to a boolean for the value to return.
var arr = [{code:'A', number: 1}, {code:'A', number: 2}, {code:'B', number: 3 }]
arr.filter(function(x) { return x.code === 'A'}).length

Iterate through the array and store the informations like count and corresponding numbers in an object structure.
var arr = [{code:'A', number: 1}, {code:'A', number: 2}, {code:'B', number: 3 }];
var obj = {};
debugger;
for (var i =0, len = arr.length; i < len; i += 1) {
ele = arr[i];
code = ele.code
if (!obj[code]) {
obj[code] = {
count: 0,
number: []
};
}
obj[code].count += 1;
obj[code].number.push(ele.number);
}
function getCount(code) {
return obj[code].count;
}
console.log(getCount('A')); // 2
console.log(getCount('B')); // 1
console.log(obj);

Related

How to create array of objects through map?

I would like to have multiple arrays of objects like this.
E.g:
const pets = [
{
name: "cat",
age: 4
},
{
name: "dog",
age: 6
}
]
But I want to create it using a map. So I was trying something like this.
let pets = [];
pets.map((item) => {
return (
item.push({
name: "cat",
age: 4
}, {
name: "dog",
age: 6
})
)
})
By this method, I'm getting an empty array.
So assuming this is incorrect, how would I go on and make this through a map.
Please any help would be appreciated.
first of all map works by looping through an array but you have empty array let pets = []; so the loop doesn't even start ! that's why you are getting empty array
Secondly map essentially is a method through which we can create a new array with the help of an existing array so you have chosen a wrong way!
example of map
const fruits = ["Mango", "Apple", "Banana", "Pineapple", "Orange"];
console.log(fruits);
const uppercaseFruits = fruits.map((fruit)=>{
return fruit.toUpperCase(); // this thing will be added to new array in every iteration
});
console.log(uppercaseFruits);
but still ....
let pets = [""]; // an item so that loop can start
const myPets = pets.map((item) => {
return (
([{
name: "cat",
age: 4
},{
name: "dog",
age: 6
}])
)
})
console.log(myPets)
//Usage of map: for example
let array = [1, 2, 3, 4, 5];
let newArray = array.map((item) => {
return item * item;
})
console.log(newArray) // [1, 4, 9, 16, 25]
map will not change the original array, if you don't assign a value to it, the original array will never be affected
And if you want to get what you want you use RANDOM like this
//random String
function randomString(e) {
e = e || 32;
var t = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678",
a = t.length,
n = "";
for (i = 0; i < e; i++) n += t.charAt(Math.floor(Math.random() * a));
return n
}
//random Number
function GetRandomNum(Min,Max)
{
var Range = Max - Min;
var Rand = Math.random();
return(Min + Math.round(Rand * Range));
}
var num = GetRandomNum(10000,999999);
alert(num);
Then you can combine random strings and random numbers into a new Object through a function

Receives an object (parameter) and returns an array

I have been trying to receive an object as a parameter and return it as an array but no luck. I don't see why it could be any problems in the code. I might be lost at this point or just completely out of the logic.
function att(testobj) {
var q = "";
for(var i = 0; i < testobj.length ; i++){
q += testobj[i] + " ";
}
return q;
}
var obj1= {
Big: 10,
low: 5
};
var attObj1= att(obj1);
console.log(attObj1);
var obj2= {
a: 10,
b: 20,
c: 30
};
var attObj2= att(obj2);
console.log(attObj2);
I did try as in the code do a for-loop where it check each array length and sort it by using q += testobj[i] but I'm not getting any results. Just a blank console log.
This article may help you object.keys()
var obj = { 0: 'a', 1: 'b', 2: 'c' };
console.log(Object.keys(obj)); // console: ['0', '1', '2']
var obj = { key0: 'value-0', key1: 'value-1', key2: 'value-2' };
console.log(Object.keys(obj)); // console: ['key0', 'key1', 'key2']
You could iterate over the keys and return the joind value.
Method used:
Object.keys for getting all keys from the object,
Array#join convert an array to a string with the given string as glue.
function att(testobj) {
return Object.keys(testobj).join(', ');
}
var obj1= {
Big: 10,
low: 5
};
var attObj1= att(obj1);
console.log(attObj1);
var obj2= {
a: 10,
b: 20,
c: 30
};
var attObj2= att(obj2);
console.log(attObj2);
Although an Array is technically an Object, one difference is that they can be iterated over.
So for example you can do:
var someArray = ['some', 'value', 'here'];
for (var i = 0; i <= someArray.length; i++) {
console.log(someArray[i]);
}
However, with an object you cannot as it doesn't contain the iterate functionality.
If you want to iterate through an Object and an Array interchangeably, you need to consider using a method that supports both.
For example:
function iterateOver(obj) {
for (var k in obj) {
console.log('Key', k, 'Value', obj[k]);
}
}
var someArray = ['some', 'value', 'here'];
var someObject = {
some: 'value',
another: 'great_value'
};
iterateOver(someArray);
iterateOver(someObject);

Generating pairs of values from a map with values as list in javascript

I have the below map.
map = { a: [ 11, -11 ], b: [ 'hello', 10 ] }
How do I get the below output from this map?
(11,'hello)
(-11,10)
Note that the number of keys in the map is dynamic. As of now there are 2 keys. I need to get the logic to work for any number of keys and any number of elements in the list for each key. Thanks.
The keys of an object are traversed in an arbitrary way, with that in mind and also assuming that each nested array has the same length you can do something like this:
var map = { a: [ 11, -11 ], b: [ 'hello', 10 ] }
// properties of the map to array e.g. ['a', 'b', ...]
var keys = Object.keys(map)
var ans = []
// k = the length of each nested array
// handles the case of an empty map {}
var k = (keys[0] && map[keys[0]].length)|0
for (var i = 0; i < k; i += 1) {
var transpose = []
for (var j = 0; j < keys.length; j += 1) {
transpose.push(map[keys[j]][i])
}
ans.push(transpose)
}
document.write(JSON.stringify(ans))
Loop though all to create output shown as string
var keys = Object.keys(map);
var out = map[keys[0]].map(function(item, i){
return '(' + [item, map[keys[1]][i]].join() + ')';
}).join('<br>');
Produces:
(11,hello)
(-11,10)
var map = { a: [ 11, -11 ], b: [ 'hello', 10 ] }
var keys = Object.keys(map);
var out = map[keys[0]].map(function(item, i){
return '('+ [item, map[keys[1]][i]].join() + ')';
}).join('<br>');
document.body.innerHTML= out;

Take highest property value and return it in an array in Javascript

I want to loop through this object and return the keys with the highest property values into an array.
Object {clear-spring: 3, deep-autumn: 2, warm-spring: 1, light-summer: 2, light-spring: 2, clear-summer: 3}
In this case, I want an array like this:
["clear-summer", "clear-spring"]
Is there an efficient way to do this with jQuery or pure javascript?
You simply need to iterate over your item once, keeping track of what ever the largest set is that you've found so far.
var a = {'clear-spring': 3, 'deep-autumn': 2, 'warm-spring': 1, 'light-summer': 2, 'light-spring': 2, 'clear-summer': 3};
var max = {
val: Number.NEGATIVE_INFINITY,
keys: []
}
for (var prop in a) {
if (a.hasOwnProperty(prop)) {
var n = a[prop];
if (n >= max.val) {
if (n > max.val) {
max.keys = [];
}
max.val = n;
max.keys.push(prop);
}
}
}
You may use for.. in to loop through the object
var object = {clear-spring: 3, deep-autumn: 2, warm-spring: 1, light-summer: 2, light-spring: 2, clear-summer: 3};
// Iterates over the oject
for (var key in object) {
if(object.hasOwnProperty(key)) {
// Key === 'clear-spring' (sample)
// object[key] === 3 (sample)
// do whatever you want
}
}
var o = {'clear-spring': 3, 'deep-autumn': 2, 'warm-spring': 1, 'light-summer': 2, 'light-spring': 2, 'clear-summer': 3};
var max = 0, result = [];
// find max:
for(var k in o) { if (o[k] > max) max = o[k] }
// find keys matching the max:
for(var k in o) { if (o[k] === max) result.push(k) }
// log result
console.log(result);
Not sure if most efficient, but first find the max value, then go back and pull out all the ones that match max value.
var obj = {'clear-spring': 3, 'deep-autumn': 2, 'warm-spring': 1, 'light-summer': 2, 'light-spring': 2, 'clear-summer': 3};
var ary = [];
var max = Number.NEGATIVE_INFINITY;
for (var prop in obj) {
if (obj[prop] > max) {
max = obj[prop];
}
}
for (var prop in obj) {
if (obj[prop] === max) {
ary.push(prop);
}
}

Calculate the average of points in a array - Javascript

I have an array with infos about a group of people : name, current status, new points, last event points
Example:
var group = new Array();
group[0] = "John Doe,beginer,14,7";
group[1] = "Lois Lane,advanced,13,9";
group[2] = "Bruce Waine,advanced,17,10";
I need a function that calculates the average of the new points.
For the previous example the average would be (14+13+17)/3 = 14.66666666666667
It'd be a heck of a lot easier if you convert the data in the array from strings to objects This will benefit you in two ways: 1) the code will be more readable, understandable, and easier to maintain, and 2) you won't have to do a bunch of string gymnastics to pull out the relevant data.
Do something like this:
var group = [
{ name: 'John Doe', status: 'beginner', newPoints: 14, eventPoints: 7 },
{ name: 'Lois Lane', status: 'advanced', newPoints: 13, eventPoints: 9 },
{ name: 'Bruce Waine', status: 'advanced', newPoints: 17, eventPoints: 10 }
];
function getAverageNewPoints(people) {
var count = people.length || 0,
average = 0;
for (var i = 0; i < count; i++) {
average += people[i].newPoints;
}
return average / count;
}
alert('The average of new points in the group is: ' + getAverageNewPoints(group));
Try the following:
function groupAverage(group) {
var sum = 0;
var count = group.length;
for (var i in group) {
sum += parseInt(group[i].split(',')[2], 10);
}
return sum / count;
}
Split the String at , and get the values and convert them to Number.
var group = new Array();
group[0] = "John Doe,beginer,14,7";
group[1] = "Lois Lane,advanced,13,9";
group[2] = "Bruce Waine,advanced,17,10";
sum=0;
for(var i in group)
{
sum=sum+Number(group[i].split(",")[2]);
}
console.log(sum/group.length);
You have a bad data structure for this. You don't want to use strings. You also should not use the Array constructor. Start with:
var group = [
{name: "John Doe", rank: "beginner", points: 14, lastScore: 7},
{name: "Lois Lane", rank: "advanced", points: 13, lastScore: 9},
{name: "Bruce Wayne", rank: "advanced", points: 17, lastScore: 10},
],
length = group.length,
sum = 0,
i;
for ( i = 0; i < length; ++i) {
sum += group[i].points;
}
return sum / length; // Or do something else with the result.
// I did no error checking.
You could use an object constructor instead of the inline Object I used, but that's not really necessary. I'm just curious; did you use strings as a default, or was using a string interface part of a textbook assignment?
Oh, one reason to use [] instead of new Array() is that when you construct an Array, the value is always truthy, while [] is falsy.
I did take the liberty of correcting Bruce's last name.

Categories

Resources