Find max value in object array [duplicate] - javascript

This question already has answers here:
Finding the max value of an attribute in an array of objects and return the entire object
(5 answers)
Finding the max value of an attribute in an array of objects
(21 answers)
Closed 4 years ago.
I have object that looks like this:
peaks =
0: {intervalId: 7, time: 1520290800000, value: 54.95125000000001}
1: {intervalId: 7, time: 1520377200000, value: 49.01083333333333}
and so on.
How do I find peak that has Max value?
I tried to do it like this
this.loadPeak = peaks.map(a => Math.max(a.value));
but I just got bunch of peaks array with value (instead of all intervalId, time, value) and not the max value.
**Thank you so much for everyone, every solution was working, sadly can't accept all. **

The main issue with sorting your array, is it causes many needless iterations through your array. This gets drastically slower the bigger your array is, sorting to try and move elements up and down. With reduce(), we can handle this in the minimum amount of steps needed, simply replacing the previous value if the current element's value is greater than the previous:
var peaks = [
{intervalId: 7, time: 1520290800000, value: 54.95125000000001},
{intervalId: 7, time: 1520377200000, value: 49.01083333333333}
];
const maxPeak = peaks.reduce((p, c) => p.value > c.value ? p : c);
console.log(maxPeak);

You could spread only the value value for Math.max.
var peaks = [{ intervalId: 7, time: 1520290800000, value: 54.95125000000001 }, { intervalId: 7, time: 1520377200000, value: 49.01083333333333 }]
max = Math.max(...peaks.map(({ value }) => value)),
object = peaks.find(({ value }) => value === max);
console.log(max);
console.log(object);

The simple way is just to use a loop:
this.loadPeak = null;
for (const peak of peaks) {
if (!this.loadPeak || peak.value > this.loadPeak.value) {
this.loadPeak = peak;
}
}
Live Example:
const peaks = [
{intervalId: 7, time: 1520290800000, value: 54.95125000000001},
{intervalId: 7, time: 1520377200000, value: 49.01083333333333}
];
let loadPeak = null;
for (const peak of peaks) {
if (!loadPeak || peak.value > loadPeak.value) {
loadPeak = peak;
}
}
console.log(loadPeak);
As with nearly any array operation, you can shoe-horn it into a reduce call if you like:
this.loadPeak = peaks.reduce((maxPeak, peak) => !maxPeak || maxPeak.value < peak.value ? peak : maxPeak, null);
const peaks = [
{intervalId: 7, time: 1520290800000, value: 54.95125000000001},
{intervalId: 7, time: 1520377200000, value: 49.01083333333333}
];
const loadPeak = peaks.reduce((maxPeak, peak) => !maxPeak || maxPeak.value < peak.value ? peak : maxPeak, null);
console.log(loadPeak);
I should have realized earlier this was a duplicate question. I've found the dupetarget, marked it, and made this a CW answer.

You can sort your peaks in descending order of value, then pick the first of the sorted array.
let peaks = [{
intervalId: 7,
time: 1520290800000,
value: 54.95125000000001
},
{
intervalId: 7,
time: 1520377200000,
value: 49.01083333333333
}
]
let sortedPeaks = peaks.sort((a, b) => b.value - a.value)
let loadPeak = sortedPeaks[0];
console.log(loadPeak);

Related

Dynamic Programming Bottoms up approach clarification [duplicate]

This question already has answers here:
What is the difference between bottom-up and top-down?
(9 answers)
Closed 1 year ago.
So I have been really trying to grasp Dynamic Programming. I can say that I really understand the memoization top down approach, but the bottoms up approach is really confusing to me. I was able to solve rods cutting top down, but I had to seek the solution for the bottoms up. I just don't understand when to use a 1D array or a 2D array. Then the for loop within the bottoms up is just confusing. Can anyone help me understand the differences in these two codes conceptually?
// Top Down Memoizaton:
const solveRodCuttingTop = function(lengths, prices, n) {
return solveRodCuttingHelper(0, lengths, prices, n);
};
function solveRodCuttingHelper(idx, span, prices, n, memo = []) {
// BASE CASES
if (idx === span.length || n <= 0 || prices.length !== span.length) {
return 0;
}
let included = 0, excluded = 0;
memo[idx] = memo[idx] || [];
if (memo[idx][n] !== undefined) return memo[idx][n];
if (span[idx] <= n) {
included = prices[idx] + solveRodCuttingHelper(idx, span, prices, n - span[idx], memo);
}
excluded = solveRodCuttingHelper(idx + 1, span, prices, n, memo);
memo[idx][n] = Math.max(included, excluded);
return memo[idx][n];
}
// Bottoms up
const solveRodCuttingBottom = function(lengths, prices, n) {
const rods = Array.from({length: n + 1});
rods[0] = 0;
let maxRevenue = - Infinity;
for (let i = 1; i < rods.length; i++) {
for (let j = 1; j <= i; j++) {
maxRevenue = Math.max(maxRevenue, prices[j - 1] + rods[i - j])
}
rods[i] = maxRevenue
}
return rods[prices.length];
};
const lengths = [1, 2, 3, 4, 5];
const prices = [2, 6, 7, 10, 13];
This is an interesting problem. Maybe I'm over-simplifying it, but if you first calculate each price per length, you can determine the solution by selling as much as possible at the highest rate. If the remaining rod is too short to sell at the best rate, move onto the next best rate and continue.
To solve using this technique, we first implement a createMarket function which takes lenghts and prices as input, and calculates a price-per-length rate. Finally the market is sorted by rate in descending order -
const createMarket = (lengths, prices) =>
lengths.map((l, i) => ({
length: l, // length
price: prices[i], // price
rate: prices[i] / l // price per length
}))
.sort((a, b) => b.rate - a.rate) // sort by price desc
const lengths = [1, 2, 3, 4, 5]
const prices = [2, 6, 7, 10, 13]
console.log(createMarket(lengths, prices))
[
{ length: 2, price: 6, rate: 3 },
{ length: 5, price: 13, rate: 2.6 },
{ length: 4, price: 10, rate: 2.5 },
{ length: 3, price: 7, rate: 2.3333333333333335 },
{ length: 1, price: 2, rate: 2 }
]
Next we write recursive solve to accept a market, [m, ...more], and a rod to cut and sell. The solution, sln, defaults to [] -
const solve = ([m, ...more], rod, sln = []) =>
m == null
? sln
: m.length > rod
? solve(more, rod, sln)
: solve([m, ...more], rod - m.length, [m, ...sln])
const result =
solve(createMarket(lengths, prices), 11)
console.log(result)
[
{ length: 1, price: 2, rate: 2 },
{ length: 2, price: 6, rate: 3 },
{ length: 2, price: 6, rate: 3 },
{ length: 2, price: 6, rate: 3 },
{ length: 2, price: 6, rate: 3 },
{ length: 2, price: 6, rate: 3 }
]
Above, solve returns the rod lengths that sum to the maximum price. If you want the total price, we can reduce the result and sum by price -
const bestPrice =
solve(createMarket(lengths, prices), 11)
.reduce((sum, r) => sum + r.price, 0)
console.log(bestPrice)
32

Is there any way to modify criteria of what values to allow in an Array?

I have an array of values. I want to make a second array based on the first one with stricter criteria. For example, what I want specifically is:
arrayOne[1,1,1,1,1,2,2,2,3,3,3,3,4,4,4,4,4,5,5,5]
How would I make it so in my new array, only the values that show up 5 times are a part of the array and only show up once. Example: arrayTwo [1,4]
I'm fairly new to JavaScript and have been given an opportunity to code a decision making system for one of my business courses instead of doing the final exam. Any help you can give would be much appreciated. Thank You.
You could use a hash table, which counts each found element and then use the count for filtering and get only the fifth element as result set in a single loop.
var array = [1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 5, 5, 5],
count = Object.create(null),
result = array.filter(v => (count[v] = (count[v] || 0) + 1) === 5);
console.log(result);
I commented the code with the steps I took:
const arrayOne = [1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 5, 5, 5];
function method(arr, minimum) {
//Create an object containing the amount each number occurs
const occurrences = arr.reduce((o, n) => {
//If number is already in the object add 1
if (o[n]) o[n] = o[n] + 1;
//Else set its occurence to 1
else o[n] = 1;
//Return the object for the next iteration
return o;
}, {});
//Deduplicate the array be creating a Set(every elements can only occur once) and spread it back into an array
const deduplicate = [...new Set(arr)];
//Filter array to only contain elements which have the minimum of occurences
const filtered = deduplicate.filter(n => occurrences[n] >= minimum);
return filtered;
}
console.log(method(arrayOne, 5));
You can use a Map for this.
let arrayOne = [1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 5, 5, 5];
let counterMap = new Map();
arrayOne.forEach(value => {
let valueStr = value.toString();
counterMap.set(valueStr, counterMap.has(valueStr) ? counterMap.get(valueStr) + 1 : 1);
});
let arrayTwo = [];
counterMap.forEach((value, key, map) => {
if(value >= 5) {
arrayTwo.push(key);
}
});
console.log(arrayTwo);
Not the most elegant answer, but I assume you're looking just to find all values that appear at least 5 times.
const arrayOne = [1,1,1,1,1,2,2,2,3,3,3,3,4,4,4,4,4,5,5,5]
const arrayTwo = Object.entries(arrayOne.reduce((obj, num) => {
if(!obj[num]){
obj[num] = 1
} else {
obj[num] = obj[num] + 1
}
return obj
}, {})).filter(([key, value]) => {
return value >= 5
}).map((item) => {
return parseInt(item[0])
})
console.log(arrayTwo)
const a = [1,1,1,1,1,2,2,2,3,3,3,3,4,4,4,4,4,5,5,5,5,5,5,5,5,5];
Define a function that will take an array and numOfOccurrences
const filterByOcur = (arr, numOfOccurrences) => {
// create an object to act as a counter this will let us
// iterate over the array only once
const counter = {};
const res = new Set();
for (let num of arr) {
// if it's the first time we see the num set counter.num to 1;
if (!counter[num]) counter[num] = 1;
// if counter.num is greater or equal to numOfOccurrences
// and we don't have the num in the set add it to the set
else if (++counter[num] >= numOfOccurrences && !res.has(num)) res.add(num);
}
// spread the Set into an array
return [...res];
};
console.log(
filterByOcur(a, 5)
);
There is number of ways of doing this, I will try to explain this step by step:
Array declaration
const a = [1,1,1,1,1,2,2,2,3,3,3,3,4,4,4,4,4,5,5,5]
Method to count elements in an array, we are using reducer function that as a first argument takes object where key is our value from array and has a incremental number as a value. Remeber to start reducer with empty object
const counted = a.reduce((counter, value) => {
if (counter[value]) counter[value]++
else counter[value] = 1
return counter
}, {})
Make your array unique with Set constructor
const uniq = Array.from(new Set(a))
Fire filter functions on the uniq array with a help of counted array, look how we access it:
const onlyOne = uniq.filter(val => counted[val] === 1)
const onlyFive = uniq.filter(val => counted[val] === 5)
Merge all filtered arrays into one
const final = [].concat(onlyOne, onlyFive)

_.sum(_.values(x)) ,if x's values are not all numbers

I have an object similar to this :
obj = { name:"myobject", MON: 3, TUE: 5}
I am trying to do a _.sum(_.values(obj)) and push that value into an array this.hours.push(_.sum(_.values(obj))) .
I am expecting an array like this [8](the reason I want to store it inside array is because I might want to parse multiple objects in the future). How do I achieve this?
Filter out the non-numbers.
const obj = { name: "myobject", MON: 3, TUE: 5 };
const numbers = _.filter(obj, x => typeof x === 'number');
const total = _.sum(numbers);
Just in case anyone need it, Adding regular way to do this apart from #mbojko answer:
const obj = { name: "myobject", MON: 3, TUE: 5 };
var total = 0;
_.forOwn(obj, function(value) {
if(typeof value === 'number')
total += value;
});
You can use _.sumBy() and return 0 for non numeric values:
const obj = { name:"myobject", MON: 3, TUE: 5}
const result = _.sumBy(_.values(obj), v => _.isNumber(v) ? v : 0)
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>

counting number of occurrences in an array [duplicate]

I have an array:
[1, 2, 3, 5, 2, 8, 9, 2]
I would like to know how many 2s are in the array.
What is the most elegant way to do it in JavaScript without looping with for loop?
[this answer is a bit dated: read the edits, in the notion of 'equal' in javascript is ambiguous]
Say hello to your friends: map and filter and reduce and forEach and every etc.
(I only occasionally write for-loops in javascript, because of block-level scoping is missing, so you have to use a function as the body of the loop anyway if you need to capture or clone your iteration index or value. For-loops are more efficient generally, but sometimes you need a closure.)
The most readable way:
[....].filter(x => x==2).length
(We could have written .filter(function(x){return x==2}).length instead)
The following is more space-efficient (O(1) rather than O(N)), but I'm not sure how much of a benefit/penalty you might pay in terms of time (not more than a constant factor since you visit each element exactly once):
[....].reduce((total,x) => (x==2 ? total+1 : total), 0)
or as a commenter kindly pointed out:
[....].reduce((total,x) => total+(x==2), 0)
(If you need to optimize this particular piece of code, a for loop might be faster on some browsers... you can test things on jsperf.com.)
You can then be elegant and turn it into a prototype function:
[1, 2, 3, 5, 2, 8, 9, 2].count(2)
Like this:
Object.defineProperties(Array.prototype, {
count: {
value: function(value) {
return this.filter(x => x==value).length;
}
}
});
You can also stick the regular old for-loop technique (see other answers) inside the above property definition (again, that would likely be much faster).
2017 edit:
Whoops, this answer has gotten more popular than the correct answer. Actually, just use the accepted answer. While this answer may be cute, the js compilers probably don't (or can't due to spec) optimize such cases. So you should really write a simple for loop:
Object.defineProperties(Array.prototype, {
count: {
value: function(query) {
/*
Counts number of occurrences of query in array, an integer >= 0
Uses the javascript == notion of equality.
*/
var count = 0;
for(let i=0; i<this.length; i++)
if (this[i]==query)
count++;
return count;
}
}
});
You could define a version .countStrictEq(...) which used the === notion of equality. The notion of equality may be important to what you're doing! (for example [1,10,3,'10'].count(10)==2, because numbers like '4'==4 in javascript... hence calling it .countEq or .countNonstrict stresses it uses the == operator.)
Caveat:
Defining a common name on the prototype should be done with care. It is fine if you control your code, but bad if everyone wants to declare their own [].count function, especially if they behave differently. You may ask yourself "but .count(query) surely sounds quite perfect and canonical"... but consider perhaps you could do something like [].count(x=> someExpr of x). In that case you define functions like countIn(query, container) (under myModuleName.countIn), or something, or [].myModuleName_count().
Also consider using your own multiset data structure (e.g. like python's 'collections.Counter') to avoid having to do the counting in the first place. This works for exact matches of the form [].filter(x=> x==???).length (worst case O(N) down to O(1)), and modified will speed up queries of the form [].filter(filterFunction).length (roughly by a factor of #total/#duplicates).
class Multiset extends Map {
constructor(...args) {
super(...args);
}
add(elem) {
if (!this.has(elem))
this.set(elem, 1);
else
this.set(elem, this.get(elem)+1);
}
remove(elem) {
var count = this.has(elem) ? this.get(elem) : 0;
if (count>1) {
this.set(elem, count-1);
} else if (count==1) {
this.delete(elem);
} else if (count==0)
throw `tried to remove element ${elem} of type ${typeof elem} from Multiset, but does not exist in Multiset (count is 0 and cannot go negative)`;
// alternatively do nothing {}
}
}
Demo:
> counts = new Multiset([['a',1],['b',3]])
Map(2) {"a" => 1, "b" => 3}
> counts.add('c')
> counts
Map(3) {"a" => 1, "b" => 3, "c" => 1}
> counts.remove('a')
> counts
Map(2) {"b" => 3, "c" => 1}
> counts.remove('a')
Uncaught tried to remove element a of type string from Multiset, but does not exist in Multiset (count is 0 and cannot go negative)
sidenote: Though, if you still wanted the functional-programming way (or a throwaway one-liner without overriding Array.prototype), you could write it more tersely nowadays as [...].filter(x => x==2).length. If you care about performance, note that while this is asymptotically the same performance as the for-loop (O(N) time), it may require O(N) extra memory (instead of O(1) memory) because it will almost certainly generate an intermediate array and then count the elements of that intermediate array.
Modern JavaScript:
Note that you should always use triple equals === when doing comparison in JavaScript (JS). The triple equals make sure, that JS comparison behaves like double equals == in other languages (there is one exception, see below). The following solution shows how to solve this the functional way, which will ensure that you will never have out of bounds error:
// Let has local scope
let array = [1, 2, 3, 5, 2, 8, 9, 2]
// Functional filter with an Arrow function
// Filter all elements equal to 2 and return the length (count)
array.filter(x => x === 2).length // -> 3
The following anonymous Arrow function (lambda function) in JavaScript:
(x) => {
const k = 2
return k * x
}
may be simplified to this concise form for a single input:
x => 2 * x
where the return is implied.
Always use triple equals: === for comparison in JS, with the exception of when checking for nullability: if (something == null) {} as it includes a check for undefined, if you only use double equals as in this case.
Very simple:
var count = 0;
for(var i = 0; i < array.length; ++i){
if(array[i] == 2)
count++;
}
2017:
If someone is still interested in the question, my solution is the following:
const arrayToCount = [1, 2, 3, 5, 2, 8, 9, 2];
const result = arrayToCount.filter(i => i === 2).length;
console.log('number of the found elements: ' + result);
Here is an ES2017+ way to get the counts for all array items in O(N):
const arr = [1, 2, 3, 5, 2, 8, 9, 2];
const counts = {};
arr.forEach((el) => {
counts[el] = counts[el] ? (counts[el] + 1) : 1;
});
You can also optionally sort the output:
const countsSorted = Object.entries(counts).sort(([_, a], [__, b]) => a - b);
console.log(countsSorted) for your example array:
[
[ '2', 3 ],
[ '1', 1 ],
[ '3', 1 ],
[ '5', 1 ],
[ '8', 1 ],
[ '9', 1 ]
]
If you are using lodash or underscore the _.countBy method will provide an object of aggregate totals keyed by each value in the array. You can turn this into a one-liner if you only need to count one value:
_.countBy(['foo', 'foo', 'bar'])['foo']; // 2
This also works fine on arrays of numbers. The one-liner for your example would be:
_.countBy([1, 2, 3, 5, 2, 8, 9, 2])[2]; // 3
Weirdest way I can think of doing this is:
(a.length-(' '+a.join(' ')+' ').split(' '+n+' ').join(' ').match(/ /g).length)+1
Where:
a is the array
n is the number to count in the array
My suggestion, use a while or for loop ;-)
Not using a loop usually means handing the process over to some method that does use a loop.
Here is a way our loop hating coder can satisfy his loathing, at a price:
var a=[1, 2, 3, 5, 2, 8, 9, 2];
alert(String(a).replace(/[^2]+/g,'').length);
/* returned value: (Number)
3
*/
You can also repeatedly call indexOf, if it is available as an array method, and move the search pointer each time.
This does not create a new array, and the loop is faster than a forEach or filter.
It could make a difference if you have a million members to look at.
function countItems(arr, what){
var count= 0, i;
while((i= arr.indexOf(what, i))!= -1){
++count;
++i;
}
return count
}
countItems(a,2)
/* returned value: (Number)
3
*/
I'm a begin fan of js array's reduce function.
const myArray =[1, 2, 3, 5, 2, 8, 9, 2];
const count = myArray.reduce((count, num) => num === 2 ? count + 1 : count, 0)
In fact if you really want to get fancy you can create a count function on the Array prototype. Then you can reuse it.
Array.prototype.count = function(filterMethod) {
return this.reduce((count, item) => filterMethod(item)? count + 1 : count, 0);
}
Then do
const myArray =[1, 2, 3, 5, 2, 8, 9, 2]
const count = myArray.count(x => x==2)
Most of the posted solutions using array functions such as filter are incomplete because they aren't parameterized.
Here goes a solution with which the element to count can be set at run time.
function elementsCount(elementToFind, total, number){
return total += number==elementToFind;
}
var ar = [1, 2, 3, 5, 2, 8, 9, 2];
var elementToFind=2;
var result = ar.reduce(elementsCount.bind(this, elementToFind), 0);
The advantage of this approach is that could easily change the function to count for instance the number of elements greater than X.
You may also declare the reduce function inline
var ar = [1, 2, 3, 5, 2, 8, 9, 2];
var elementToFind=2;
var result = ar.reduce(function (elementToFind, total, number){
return total += number==elementToFind;
}.bind(this, elementToFind), 0);
Really, why would you need map or filter for this?
reduce was "born" for these kind of operations:
[1, 2, 3, 5, 2, 8, 9, 2].reduce( (count,2)=>count+(item==val), 0);
that's it! (if item==val in each iteration, then 1 will be added to the accumulator count, as true will resolve to 1).
As a function:
function countInArray(arr, val) {
return arr.reduce((count,item)=>count+(item==val),0)
}
Or, go ahead and extend your arrays:
Array.prototype.count = function(val) {
return this.reduce((count,item)=>count+(item==val),0)
}
It is better to wrap it into function:
let countNumber = (array,specificNumber) => {
return array.filter(n => n == specificNumber).length
}
countNumber([1,2,3,4,5],3) // returns 1
I use this:
function countElement(array, element) {
let tot = 0;
for(var el of array) {
if(el == element) {
tot++;
}
}
return tot;
}
var arr = ["a", "b", "a", "c", "d", "a", "e", "f", "a"];
console.log(countElement(arr, "a")); // 4
var arrayCount = [1,2,3,2,5,6,2,8];
var co = 0;
function findElement(){
arrayCount.find(function(value, index) {
if(value == 2)
co++;
});
console.log( 'found' + ' ' + co + ' element with value 2');
}
I would do something like that:
var arrayCount = [1,2,3,4,5,6,7,8];
function countarr(){
var dd = 0;
arrayCount.forEach( function(s){
dd++;
});
console.log(dd);
}
I believe what you are looking for is functional approach
const arr = ['a', 'a', 'b', 'g', 'a', 'e'];
const count = arr.filter(elem => elem === 'a').length;
console.log(count); // Prints 3
elem === 'a' is the condition, replace it with your own.
Array.prototype.count = function (v) {
var c = 0;
for (let i = 0; i < this.length; i++) {
if(this[i] === v){
c++;
}
}
return c;
}
var arr = [1, 2, 3, 5, 2, 8, 9, 2];
console.log(arr.count(2)); //3
Solution by recursion
function count(arr, value) {
if (arr.length === 1) {
return arr[0] === value ? 1 : 0;
} else {
return (arr.shift() === value ? 1 : 0) + count(arr, value);
}
}
count([1,2,2,3,4,5,2], 2); // 3
Create a new method for Array class in core level file and use it all over your project.
// say in app.js
Array.prototype.occurrence = function(val) {
return this.filter(e => e === val).length;
}
Use this anywhere in your project -
[1, 2, 4, 5, 2, 7, 2, 9].occurrence(2);
// above line returns 3
Here is a one liner in javascript.
Use map. Find the matching values (v === 2) in the array, returning an array of ones and zeros.
Use Reduce. Add all the values of the array for the total number found.
[1, 2, 3, 5, 2, 8, 9, 2]
.map(function(v) {
return v === 2 ? 1 : 0;
})
.reduce((a, b) => a + b, 0);
The result is 3.
Depending on how you want to run it:
const reduced = (array, val) => { // self explanatory
return array.filter((element) => element === val).length;
}
console.log(reduced([1, 2, 3, 5, 2, 8, 9, 2], 2));
// 3
const reducer = (array) => { // array to set > set.forEach > map.set
const count = new Map();
const values = new Set(array);
values.forEach((element)=> {
count.set(element, array.filter((arrayElement) => arrayElement === element).length);
});
return count;
}
console.log(reducer([1, 2, 3, 5, 2, 8, 9, 2]));
// Map(6) {1 => 1, 2 => 3, 3 => 1, 5 => 1, 8 => 1, …}
You can use built-in function Array.filter()
array.filter(x => x === element).length;
var arr = [1, 2, 3, 5, 2, 8, 9, 2];
// Count how many 2 there are in arr
var count = arr.filter(x => x === 2).length;
console.log(count);
One-liner function
const countBy = (a,f)=>a.reduce((p,v,i,x)=>p+!!f(v,i,x), 0)
countBy([1,2,3,4,5], v=>v%2===0) // 2
There are many ways to find out. I think the easiest way is to use the array filter method which is introduced in es6.
function itemCount(array, item) {
return array.filter(element => element === item).length
}
const myArray = [1,3,5,7,1,2,3,4,5,1,9,0,1]
const items = itemCount(myArray, 1)
console.log(items)
Something a little more generic and modern (in 2022):
import {pipe, count} from 'iter-ops';
const arr = [1, 2, 3, 5, 2, 8, 9, 2];
const n = pipe(arr, count(a => a === 2)).first; //=> 3
What's good about this:
It counts without creating a new array, so it is memory-efficient
It works the same for any Iterable and AsyncIterable
Another approach using RegExp
const list = [1, 2, 3, 5, 2, 8, 9, 2]
const d = 2;
const counter = (`${list.join()},`.match(new RegExp(`${d}\\,`, 'g')) || []).length
console.log(counter)
The Steps follows as below
Join the string using a comma Remember to append ',' after joining so as not to have incorrect values when value to be matched is at the end of the array
Match the number of occurrence of a combination between the digit and comma
Get length of matched items
I believe you can use the new Set array method of JavaScript to have unique values.
Example:
var arr = [1, 2, 3, 5, 2, 8, 9, 2]
var set = new Set(arr);
console.log(set);
// 1,2,3,5,8,9 . We get unique values as output.
You can use length property in JavaScript array:
var myarray = [];
var count = myarray.length;//return 0
myarray = [1,2];
count = myarray.length;//return 2

Finding the max on collection of objects?

How can I find the max cell value in a collection of objects using lodash while ignoring one of the keys.
var data = [{
tick: 0,
valueA: 3,
valueB: 2
}, {
tick: 6,
valueA: 6,
valueB: 3
}, {
tick: 12,
valueA: 2,
valueB: 4
}, ...];
I want to find the max tick, this is the row identifier, and the max of all other values. What I have so far is:
var maxTick = _.max(data, 'tick'),
maxValue = _.max(data, function(o) { return _.max(_.values(o))};);
How can I let maxValue ignore the tick data?
Along T Nguyen's line of thought but use _.omit instead of pick that way you only have to omit tick
_.max(data, function(o){_.omit(o, "tick")})
You just need a function which iterates through all elements properties and a list of ignored properties.
Here is a sample:
var findMax = function(list, ignoredFields){
var maxValue = null;
for(var i=0;i<list.length;i++){
for(var prop in list[i]){
if(ignoredFields.indexOf(prop) < 0){
maxValue = maxValue < list[i][prop] ? list[i][prop] : maxValue;
}
}
}
return maxValue;
}
And you execute the function with your data and the list of ignored properties
findMax(data,['tick'])
Update: modified the function to use lodash iterations
var findMax = function(list, ignoredFields){
var maxValue = null;
_.forEach(list, function(element, index) {
var _localMax = _.max(_.omit(element, ignoredFields));
maxValue = maxValue < _localMax ? _localMax : maxValue;
});
return maxValue;
}
Try using _.pick() to pick out all keys except tick then run your max function on that new collection. By the way, your maxValue function doesn't seem right. Are you saying that you want to take the highest scalar valuer in any object, or the object which contains the highest scalar value (except tick)?
UPDATE: Based on your response, try this: http://jsfiddle.net/tonicboy/Xxf9E/1/
var data = [{
tick: 0,
valueA: 3,
valueB: 2
}, {
tick: 6,
valueA: 6,
valueB: 3
}, {
tick: 12,
valueA: 2,
valueB: 4
}],
data2 = [];
_.each(data, function(element, index) {
var values = _.values(_.omit(element, 'tick'));
data2 = data2.concat(values);
});
console.log(data2);
console.log(_.max(data2));

Categories