So, I have something like this:
objArray1 = [ { candidate1: "Alex" , votes: 4}, { candidate2: "Paul", votes: 3}];
objArray2 = [ { candidate1: "Alex" , votes: 7}, { candidate2: "Ben", votes: 3}, { candidate3: "Melisa", votes:8 }];
I am trying to use javascript to make an array with all the candidates and see how many votes each of them have. The part to calculate the votes is easy, but I don't know how to put all the candidates in one array.
I should get an array with: Alex, Paul, Ben and Melisa.
Thank you!
You could use a hashtable and group by name.
var array1 = [ { candidate1: "Alex" , votes: 4}, { candidate2: "Paul", votes: 3}],
array2 = [ { candidate1: "Alex" , votes: 7}, { candidate2: "Ben", votes: 3}, { candidate3: "Melisa", votes:8 }],
grouped = [array1, array2].reduce(function (hash) {
return function (r, a) {
a.forEach(function (o, i) {
var name = o['candidate' + (i + 1)];
if (!hash[name]) {
hash[name] = { candidate: name, votes: 0 };
r.push(hash[name]);
}
hash[name].votes += o.votes;
});
return r;
};
}(Object.create(null)), []);
console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }
var candidates = [];
var found = 0;
for(var i=0;objArray1.length>i;i++){
found = 0;
//add votes to candidate array
for(var j=0;candidates.length>j;j++){
if(candidates[j].name==objArray1[i][Object.keys(objArray1[i])[0]]){
candidates[j].votes = candidates[j].votes+objArray1[i].votes;
found = 1;
}
}
//if condidate not found in votes array, create new
if(found==0){
var tmp = {};
tmp.name = objArray1[i].candidate;
tmp.votes = objArray1[i].votes;
//add to array
candidates.push(tmp);
}
}
console.log(candidates);
Generate an object which holds property name as name and vote count as value.
var objArray1 = [ { candidate1: "Alex" , votes: 4}, { candidate2: "Paul", votes: 3}], objArray2 = [ { candidate1: "Alex" , votes: 7}, { candidate2: "Ben", votes: 3}, { candidate3: "Melisa", votes:8 }];
var res = []
// cobine two arrays
.concat(objArray1, objArray2)
// iterate over the arrays
.reduce(function(obj, o) {
// get the key except the votes
var key = Object.keys(o).find(function(k) {
return k != 'votes';
})
// define property if not already defined
obj[key] = obj[key] || 0;
// add the vote count
obj[key] += o.votes;
// return object refernece
return obj;
// set initial value as empty object
}, {});
console.log(res);
// get the names array if need
console.log(Object.keys(res));
Short solution using Array.prototype.concat(), Array.prototype.reduce() and Array.prototype.map() functions:
var objArray1 = [ { candidate1: "Alex" , votes: 4}, { candidate2: "Paul", votes: 3}],
objArray2 = [ { candidate1: "Alex" , votes: 7}, { candidate2: "Ben", votes: 3}, { candidate3: "Melisa", votes:8 }],
grouped = objArray1.concat(objArray2).reduce(function(r, o){
var k = Object.keys(o).filter(function(k){
return k.indexOf('candidate') === 0;
})[0];
(r[o[k]])? r[o[k]].votes += o.votes : r[o[k]] = {candidate: o[k], votes: o.votes};
return r;
}, {}),
result = Object.keys(grouped).map(function(k){ return grouped[k]; });
console.log(result);
To get the list of names as you asked
var rawArrays = objArray1.concat(objArray2), Candidates = [], tmp = []
for (var i in rawArrays) {
tmp[rawArrays[i][Object.keys(rawArrays[i])[0]]] = 1
}
Candidates = Object.keys(tmp)
To get array with candidates and votes sum
var rawArrays = objArray1.concat(objArray2), Candidates = []
for (var i in rawArrays) {
name = rawArrays[i][Object.keys(rawArrays[i])[0]]
if (Candidates[name]) Candidates[name] += rawArrays[i].votes
else Candidates[name] = rawArrays[i].votes
}
Related
i have to make a object from array then i can work with it letter.
i am trying this code it work's but output getting only last one
let datas = "team1 1, team2 2, team3 3";
let teamdata = datas.split(" ");
var myObj = (function () {
var result = { Tname: null, count: null };
datas.split(/\s*\,\s*/).forEach(function (el) {
var parts = el.split(/\s* \s*/);
result.Tname = parts[0];
result.count = parseInt(parts[1]);
});
return result;
})();
console.log(myObj);
output getting { Tname: 'team3', count: 3 }
need output
[{name: "team1", count: 1},
{name: "team2", count: 2},
{name: "team3", count: 3}]
Simply, You could do it with
String.split() and Array.map()
let datas = "team1 1, team2 2, team3 3";
let teamdata = datas.split(", "); // ['team1 1', 'team2 2', 'team3 3']
let result = teamdata.map(team=>({team:team.split(/\s+/)[0],count:+team.split(/\s+/)[1]}))
console.log(result);
expected output:
[{name: "team1", count: 1},
{name: "team2", count: 2},
{name: "team3", count: 3}]
i have to make a object
But you then claim that your expected output is an array, not an object:
[
{name: "team1", count: 1},
{name: "team2", count: 2},
{name: "team3", count: 3}
]
In that case, make an array and then .push() to that array within the loop:
var result = [];
datas.split(/\s*\,\s*/).forEach(function (el) {
var parts = el.split(/\s* \s*/);
result.push({
Tname: parts[0],
count: parseInt(parts[1])
});
});
return result;
This should work fine:
let datas = "team1 1, team2 2, team3 3";
var results = [];
var myObj = (function () {
var result = { Tname: null, count: null };
datas.split(/\s*\,\s*/).forEach(function (el) {
var parts = el.split(/\s* \s*/);
result.Tname = parts[0];
result.count = parseInt(parts[1]);
results.push(result);
});
return results;
})();
console.log(results)
The problem with your code was that you successfully splitted the string and converted it to the object but as you are expecting the result to be in the array you were not storing the object rather were rewriting the same object time and again.
I have two arrays of objects.Where each object has different properties, Like this
let array1=[
{id:121122,name:"Matt Jeff"},
{id:121123,name:"Philip Jeff"},
{id:121124,name:"Paul Jeff"}]
let array2=[
{owner_id:121122,id:1211443,value:18},
{owner_id:121127,id:1211428,value:22}]
How can I check if the owner_id in the array2 is equal to the id in array1 then return the new array like this
let newArray=[
{owner_id:121122,id:1211443,value:18}
]
Where the owner_id in array2 is equal to the id in array1.
If I correctly understand what you need, you could do like this:
let array1 = [{
id: 121122,
name: "Matt Jeff"
}, {
id: 121123,
name: "Philip Jeff"
}, {
id: 121124,
name: "Paul Jeff"
}
]
let array2 = [{
owner_id: 121122,
id: 1211443,
value: 18
}, {
owner_id: 121127,
id: 1211428,
value: 22
}
]
const result = array2.filter(({ owner_id }) => array1.some(({ id }) => id === owner_id));
console.log(result);
You could try with nested for like:
let array1=[
{id:121122,name:"Matt Jeff"},
{id:121123,name:"Philip Jeff"},
{id:121124,name:"Paul Jeff"}]
let array2=[
{owner_id:121122,id:1211443,value:18},
{owner_id:121127,id:1211428,value:22}];
let result = [];
for(let i = 0; i < array1.length; i++) {
for(let j = 0; j < array2.length; j++) {
if (array1[i].id === array2[j].owner_id) {
result.push(array2[j]);
}
}
}
console.log(result)
EFFICIENT WAY: Using Set and filter
O(m) - Iterating on array1 and Storing the id in Set
O(n) - Iterating on the array2 and filtering the result which include O(1) to search in Set;
let array1 = [
{ id: 121122, name: "Matt Jeff" },
{ id: 121123, name: "Philip Jeff" },
{ id: 121124, name: "Paul Jeff" },
];
let array2 = [
{ owner_id: 121122, id: 1211443, value: 18 },
{ owner_id: 121127, id: 1211428, value: 22 },
];
const dict = new Set();
array1.forEach((o) => dict.add(o.id));
const result = array2.filter((o) => dict.has(o.owner_id));
console.log(result);
I have two arrays of objects(arr1 and arr2). I want to select objects from arr1 where arr1.id == arr2.typeId and add to result arr2.Price
var arr1 =
[{"id":20,"name":"name1"},
{"id":24,"name":"name2"},
{"id":25,"name":"name3"},
{"id":28,"name":"name4"},
{"id":29,"name":"name5"}]
var arr2 =
[{"typeId":20,"Price":500},
{"typeId":24,"Price":1100},
{"typeId":28,"Price":1000}]
How can I get the following?
var result =
[{"item":{"id":20,"name":"name1"}, "price":"500"}},
{{"item":{"id":24,"name":"name2"}, "price":"1100"},
{{"item":{"id":28,"name":"name4"}, "price":"1000"}]
var result = arr1.filter(function(obj1){
return arr2.some(function(obj2){
return obj1.id === obj2.typeId;
});
})
You can use reduce() on arr2 and then check if object with same id exists in arr1 with find().
var arr1 =
[{"id":20,"name":"name1"},
{"id":24,"name":"name2"},
{"id":25,"name":"name3"},
{"id":28,"name":"name4"},
{"id":29,"name":"name5"}]
var arr2 =
[{"typeId":20,"Price":500},
{"typeId":24,"Price":1100},
{"typeId":28,"Price":1000}]
var result = arr2.reduce(function(r, e) {
var c = arr1.find(a => e.typeId == a.id)
if(c) r.push({item: c, price: e.Price})
return r
}, [])
console.log(result)
You could create an object without any prototypes with Object.create as hash table and push the new object only if both arrays have a common id.
var arr1 = [{ id: 20, name: "name1" }, { id: 24, name: "name2" }, { id: 25, name: "name3" }, { id: 28, name: "name4" }, { id: 29, name: "name5" }],
arr2 = [{ typeId: 20, Price: 500 }, { typeId: 24, Price: 1100 }, { typeId: 28, Price: 1000 }],
hash = Object.create(null),
result = [];
arr1.forEach(function (a) {
hash[a.id] = a;
});
arr2.forEach(function (a) {
if (hash[a.typeId]) {
result.push({ item: hash[a.typeId], price: a.Price });
}
});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Another approach, using Array#forEach.
var arr1 = [{id:20,name:"name1"},{id:24,name:"name2"},{id:25,name:"name3"},{id:28,name:"name4"},{id:29,name:"name5"}],
arr2 = [{typeId:20,Price:500},{typeId:24,Price:1100},{typeId:28,Price:1e3}],
result = [];
arr2.forEach(function(v){
var elem = arr1.find(c => c.id == v.typeId); //find corresponding element from the `arr1` array
result.push({item: elem, price: v.Price}); //push an object containing `item` and `price` keys into the result array
});
console.log(result); //reveal the result
I have an array of objects:
var array = [{
id: "cards",
amount: 5
}, {
id: "shirts",
amount: 3
}, {
id: "cards",
amount: 2
}, {
id: "shirts",
amount: 3
}]
What I need to do is loop through this array and find the total of all id types.
So in this example, I would find the total amount of cards and shirts.
I'm not sure how to do this with objects. I've tried stripping the objects down with Object.values(array), but is there a way to do it with the objects?
Thanks for your help.
This should do what you want:
var array = [
{ id: "cards", amount: 5 },
{ id: "shirts", amount: 3 },
{ id: "cards", amount: 2 },
{ id: "shirts", amount: 3 }
];
var result = array.reduce(function(entities, item) {
entities[item.id] = (entities[item.id] || 0) + item.amount;
return entities;
}, {})
console.log(result);
You would loop your array, check the id property for your target object, then enumerate and outer scope variable with the value stored in the amount property.
var totalShirts = 0;
var totalCards = 0;
for(var i = 0, len = array.length; i < len; i++){
var entry = array[i];
if(entry.id === "cards"){
totalCards += entry.amount;
}
else if(entry.id === "shirts"){
totalShirts += entry.amount;
}
}
console.log("Total Cards: " + totalCards);
console.log("Total Shirts: " + totalShirts);
Here is an example that gets the total of each item
var array = [{id:"cards", amount: 5}, {id:"shirts", amount: 3}, {id:"cards", amount: 2}, {id:"shirts", amount: 3}];
var result = array.reduce(function(accumulator, current) {
if (!(current.id in accumulator)) {
accumulator[current.id] = current.amount;
} else {
accumulator[current.id] += current.amount;
}
return accumulator;
}, {});
console.log(result);
A simple forEach will do the trick:
var counts = {}
array.forEach(v => {
counts[v.id] = (counts[v.id] || 0) + v.amount
})
console.log(counts)
will print:
{
cards: 7
shirts: 6
}
Here is a O(n) time solution.
var totals = new Object();
for(var i = 0;i < array.length;i ++) {
var id = array[i].id;
var amount = array[i].amount;
if(totals[id] == undefined) {
totals[id] = amount;
} else {
totals[id] += amount;
}
}
console.log(totals);
You can use for..of loop
var array = [{
id: "cards",
amount: 5
}, {
id: "shirts",
amount: 3
}, {
id: "cards",
amount: 2
}, {
id: "shirts",
amount: 3
}]
let res = {};
for (let {id,amount} of array) {
if (!res.hasOwnProperty(id)) res[id] = 0;
res[id] += amount;
}
console.log(res);
Use a for-loop to do this:
var totalCards = 0;
var totalShirt = 0;
for (var i = 0; i < arr.length; i++) {
if (arr[i].id === "cards") {
totalCards += arr[i].amount;
} else {
totalShirt += arr[i].amount;
}
}
Do the magic in for loop. This example should be general enough:
var array = [ {id:"cards", amount: 5}, {id:"shirts", amount: 3}, {id:"cards", amount: 2}, {id:"shirts", amount: 3} ];
var output = [];
for(var i of array) {
if(!output[i.id]) {
output[i.id] = 0;
}
output[i.id] += i.amount;
}
console.log(output);
var array = [{id:"cards", amount: 5}, {id:"shirts", amount: 3}, {id:"cards", amount: 2}, {id:"shirts", amount: 3}];
var arr = [];
array.forEach(v => arr.push(v.id));
var newArr = [...new Set(arr)];
var arr2 = [];
newArr.forEach(function(v) {
var obj = {};
obj.id = v;
obj.counter = 0;
arr2.push(obj);
});
arr2.forEach(v => array.forEach(c => c.id == v.id ? v.counter += c.amount : v));
console.log(arr2);
You can use Array.forEach() to iterate over each element of the array. The total object is an associative array where the index is the id field of array element objects.
var array = [{ id: "cards", amount: 5 },
{ id: "shirts", amount: 3 },
{ id: "cards", amount: 2},
{ id: "shirts", amount: 3 }];
var total = {};
array.forEach(function (el) {
if (total[el.id]) {
total[el.id] += el.amount
} else {
total[el.id] = el.amount
}
});
console.log(JSON.stringify(total));
You could use Array#reduce and sum the amount.
var array = [{ id: "cards", amount: 5 }, { id: "shirts", amount: 3 }, { id: "cards", amount: 2 }, { id: "shirts", amount: 3 }],
result = array.reduce(function (r, a) {
r[a.id] = (r[a.id] || 0) + a.amount;
return r;
}, {});
console.log(result);
You can use this code
if (!Object.keys) {
Object.keys = function (obj) {
var keys = [],
k;
for (k in obj) {
if (Object.prototype.hasOwnProperty.call(obj, k)) {
keys.push(k);
}
}
return keys;
};
}
then you can do this in older browsers as well:
var len = Object.keys(obj).length;
I have an array with repeating values. I would like to find the number of occurrences for any given value.
For example, if I have an array defined as so: var dataset = [2,2,4,2,6,4,7,8];, I want to find the number of occurrences of a certain value in the array. That is, the program should show that if I have 3 occurrences of the value 2, 1 occurrence of the value 6, and so on.
What's the most idiomatic/elegant way to do this?
reduce is more appropriate here than filter as it doesn't build a temporary array just for counting.
var dataset = [2,2,4,2,6,4,7,8];
var search = 2;
var count = dataset.reduce(function(n, val) {
return n + (val === search);
}, 0);
console.log(count);
In ES6:
let count = dataset.reduce((n, x) => n + (x === search), 0);
Note that it's easy to extend that to use a custom matching predicate, for example, to count objects that have a specific property:
people = [
{name: 'Mary', gender: 'girl'},
{name: 'Paul', gender: 'boy'},
{name: 'John', gender: 'boy'},
{name: 'Lisa', gender: 'girl'},
{name: 'Bill', gender: 'boy'},
{name: 'Maklatura', gender: 'girl'}
]
var numBoys = people.reduce(function (n, person) {
return n + (person.gender == 'boy');
}, 0);
console.log(numBoys);
Counting all items, that is, making an object like {x:count of xs} is complicated in javascript, because object keys can only be strings, so you can't reliably count an array with mixed types. Still, the following simple solution will work well in most cases:
count = function (ary, classifier) {
classifier = classifier || String;
return ary.reduce(function (counter, item) {
var p = classifier(item);
counter[p] = counter.hasOwnProperty(p) ? counter[p] + 1 : 1;
return counter;
}, {})
};
people = [
{name: 'Mary', gender: 'girl'},
{name: 'Paul', gender: 'boy'},
{name: 'John', gender: 'boy'},
{name: 'Lisa', gender: 'girl'},
{name: 'Bill', gender: 'boy'},
{name: 'Maklatura', gender: 'girl'}
];
// If you don't provide a `classifier` this simply counts different elements:
cc = count([1, 2, 2, 2, 3, 1]);
console.log(cc);
// With a `classifier` you can group elements by specific property:
countByGender = count(people, function (item) {
return item.gender
});
console.log(countByGender);
2017 update
In ES6, you use the Map object to reliably count objects of arbitrary types.
class Counter extends Map {
constructor(iter, key=null) {
super();
this.key = key || (x => x);
for (let x of iter) {
this.add(x);
}
}
add(x) {
x = this.key(x);
this.set(x, (this.get(x) || 0) + 1);
}
}
// again, with no classifier just count distinct elements
results = new Counter([1, 2, 3, 1, 2, 3, 1, 2, 2]);
for (let [number, times] of results.entries())
console.log('%s occurs %s times', number, times);
// counting objects
people = [
{name: 'Mary', gender: 'girl'},
{name: 'John', gender: 'boy'},
{name: 'Lisa', gender: 'girl'},
{name: 'Bill', gender: 'boy'},
{name: 'Maklatura', gender: 'girl'}
];
chessChampions = {
2010: people[0],
2012: people[0],
2013: people[2],
2014: people[0],
2015: people[2],
};
results = new Counter(Object.values(chessChampions));
for (let [person, times] of results.entries())
console.log('%s won %s times', person.name, times);
// you can also provide a classifier as in the above
byGender = new Counter(people, x => x.gender);
for (let g of ['boy', 'girl'])
console.log("there are %s %ss", byGender.get(g), g);
A type-aware implementation of Counter can look like this (Typescript):
type CounterKey = string | boolean | number;
interface CounterKeyFunc<T> {
(item: T): CounterKey;
}
class Counter<T> extends Map<CounterKey, number> {
key: CounterKeyFunc<T>;
constructor(items: Iterable<T>, key: CounterKeyFunc<T>) {
super();
this.key = key;
for (let it of items) {
this.add(it);
}
}
add(it: T) {
let k = this.key(it);
this.set(k, (this.get(k) || 0) + 1);
}
}
// example:
interface Person {
name: string;
gender: string;
}
let people: Person[] = [
{name: 'Mary', gender: 'girl'},
{name: 'John', gender: 'boy'},
{name: 'Lisa', gender: 'girl'},
{name: 'Bill', gender: 'boy'},
{name: 'Maklatura', gender: 'girl'}
];
let byGender = new Counter(people, (p: Person) => p.gender);
for (let g of ['boy', 'girl'])
console.log("there are %s %ss", byGender.get(g), g);
array.filter(c => c === searchvalue).length;
Here is one way to show ALL counts at once:
var dataset = [2, 2, 4, 2, 6, 4, 7, 8];
var counts = {}, i, value;
for (i = 0; i < dataset.length; i++) {
value = dataset[i];
if (typeof counts[value] === "undefined") {
counts[value] = 1;
} else {
counts[value]++;
}
}
console.log(counts);
// Object {
// 2: 3,
// 4: 2,
// 6: 1,
// 7: 1,
// 8: 1
//}
Newer browsers only due to using Array.filter
var dataset = [2,2,4,2,6,4,7,8];
var search = 2;
var occurrences = dataset.filter(function(val) {
return val === search;
}).length;
console.log(occurrences); // 3
const dataset = [2,2,4,2,6,4,7,8];
const count = {};
dataset.forEach((el) => {
count[el] = count[el] + 1 || 1
});
console.log(count)
// {
// 2: 3,
// 4: 2,
// 6: 1,
// 7: 1,
// 8: 1
// }
Using a normal loop, you can find the occurrences consistently and reliably:
const dataset = [2,2,4,2,6,4,7,8];
function getNumMatches(array, valToFind) {
let numMatches = 0;
for (let i = 0, j = array.length; i < j; i += 1) {
if (array[i] === valToFind) {
numMatches += 1;
}
}
return numMatches;
}
alert(getNumMatches(dataset, 2)); // should alert 3
DEMO: https://jsfiddle.net/a7q9k4uu/
To make it more generic, the function could accept a predicate function with custom logic (returning true/false) which would determine the final count. For example:
const dataset = [2,2,4,2,6,4,7,8];
function getNumMatches(array, predicate) {
let numMatches = 0;
for (let i = 0, j = array.length; i < j; i += 1) {
const current = array[i];
if (predicate(current) === true) {
numMatches += 1;
}
}
return numMatches;
}
const numFound = getNumMatches(dataset, (item) => {
return item === 2;
});
alert(numFound); // should alert 3
DEMO: https://jsfiddle.net/57en9nar/1/
You can count all items in an array, in a single line, using reduce.
[].reduce((a,b) => (a[b] = a[b] + 1 || 1) && a, {})
This will yield an object, whose keys are the distinct elements in the array and values are the count of occurences of elements in the array. You can then access one or more of the counts by accessing a corresponding key on the object.
For example if you were to wrap the above in a function called count():
function count(arr) {
return arr.reduce((a,b) => (a[b] = a[b] + 1 || 1) && a, {})
}
count(['example']) // { example: 1 }
count([2,2,4,2,6,4,7,8])[2] // 3
You can do with use of array.reduce(callback[, initialValue]) method in JavaScript 1.8
var dataset = [2,2,4,2,6,4,7,8],
dataWithCount = dataset.reduce( function( o , v ) {
if ( ! o[ v ] ) {
o[ v ] = 1 ;
} else {
o[ v ] = o[ v ] + 1;
}
return o ;
}, {} );
// print data with count.
for( var i in dataWithCount ){
console.log( i + 'occured ' + dataWithCount[i] + 'times ' );
}
// find one number
var search = 2,
count = dataWithCount[ search ] || 0;
I've found it more useful to end up with a list of objects with a key for what is being counted and a key for the count:
const data = [2,2,4,2,6,4,7,8]
let counted = []
for (var c of data) {
const alreadyCounted = counted.map(c => c.name)
if (alreadyCounted.includes(c)) {
counted[alreadyCounted.indexOf(c)].count += 1
} else {
counted.push({ 'name': c, 'count': 1})
}
}
console.log(counted)
which returns:
[ { name: 2, count: 3 },
{ name: 4, count: 2 },
{ name: 6, count: 1 },
{ name: 7, count: 1 },
{ name: 8, count: 1 } ]
It isn't the cleanest method, and if anyone knows how to achieve the same result with reduce let me know. However, it does produce a result that's fairly easy to work with.
First, you can go with Brute Force Solution by going with Linear Search.
public int LinearSearchcount(int[] A, int data){
int count=0;
for(int i=0;i<A.length;i++) {
if(A[i]==data) count++;
}
return count;
}
However, for going with this, we get Time complexity as O(n).But by going with Binary search, we can improve our Complexity.
If you try to do it this way, you might get an error like the one below.
array.reduce((acc, arr) => acc + (arr.label === 'foo'), 0); // Operator '+' cannot be applied to type 'boolean'.
One solution would be to do it this way
array = [
{ id: 1, label: 'foo' },
{ id: 2, label: 'bar' },
{ id: 3, label: 'foo' },
{ id: 4, label: 'bar' },
{ id: 5, label: 'foo' }
]
array.reduce((acc, arr) => acc + (arr.label === 'foo' ? 1 : 0), 0); // result: 3