Counting Object Length based on key value [duplicate] - javascript

This question already has answers here:
How can I only keep items of an array that match a certain condition?
(3 answers)
Closed 8 years ago.
I have a JS object/ associative array with some values:
var array =[
{val:1,ref:10,rule:100},
{val:1,ref:12,rule:120},
{val:2,ref:13,rule:165},
];
And I want to perform a .length, but want to be able to slice based on one of the keys (for instance val == 1). I want the length of values with val 1 rather than the length of the entire object. I have looked through the references material and could not find a satisfactory answer and I am unsure if this is feasible.
array.val==1.length = 2
Something like that...

You want to .filter the array for elements that match some predicate:
var filteredArray = array.filter(function(element) { return element.val == 1 })
filteredArray.length // = 2
filter applies the callback function to each element in the array, and the new filtered array contains all elements from original array for which the filter callback function returned true. Here, the function returns true for all elements with a val property of 1.

You need to use a .filter():
array.filter(function(v){return v.val==1}).length

Related

How to manipulate an array, eliminating the empty items? [duplicate]

This question already has answers here:
How can I remove a specific item from an array in JavaScript?
(142 answers)
How to remove item from array by value? [duplicate]
(37 answers)
Closed 2 months ago.
I have an array which has some empty items.
const array = ["a","","c","","e","f","g"]
I am trying to eliminate empty items and leave only the items having string. I mean manipulating the array as:
array = ["a","c","e","f","g"]
There are many alternative like array.map, array.filter, array.slice, array.splice.. What is the most costless and recommended way of doing this?
As far as I know most cost effective way is to use the array filter method:
const array = ["a","","c","","e","f","g"];
const results = array.filter(element => {
return element !== '';
});
console.log(results);

JavaScript: Extract one number value out of key-value array and store them in a Variable [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed last year.
I do an InfluxDB query and get exact one result row like this:
{"result":[[{"result":"_result","table":0,"_start":"2022-01-28T09:00:12.676771291Z","_stop":"2022-01-29T09:00:12.676771291Z","_measurement":"Strom.Heizung.Energie_in_der_letzten_Stunde","_value":14.683000000000117,"_time":"2022-01-29T09:00:12.676771291Z","ts":1643446812676}]],"ts":1643446812684,"error":null}
I need the value of the _value key in a variable e.g. value. In this example the 14.683000000000117
I tried it with the map-function:
value = query.result[0].map(elm => (elm._value));
but I get the value in brackets like [14.683000000000117]
How can I get the number in my value variable?
Thanks
Frank
map() returns an array, even if it's an array of length 1. So, you want to retrieve the first element of the array it returns. You can achieve that by appending [0] at the end:
value = query.result[0].map(elm => (elm._value))[0];
Learn more on accessing array elements here, in the "Accessing Array Elements" section: https://www.w3schools.com/js/js_arrays.asp

How to determine if an array includes another array in JS? [duplicate]

This question already has answers here:
Why Array.indexOf doesn't find identical looking objects
(8 answers)
Closed 3 years ago.
I'm wondering what the best way to determine the membership of one array in another array in JS.
Here's an example
let a = [];
a.push([1,2]);
a.includes([1,2]) <- evaluates to false
a.indexOf([1,2]) <- evaluates to -1
What's the deal here? Any efficient work around?
At the moment, your search array doesn't actually equal the array within your a array as they have 2 different references in memory. However, you could convert your arrays to strings, such that your search can equal another string array within your array.
To do this you could convert your inner arrays to string using .map(JSON.stringify) and then search for the string version of your array using .includes(JSON.stringify(search_arrr)).
See example below:
let a = [];
let search = [1, 2];
a.push([1,2]);
a = a.map(JSON.stringify)
console.log(a.includes(JSON.stringify(search)));

push value in map of arrays at a specific postition [duplicate]

This question already has answers here:
How can I create a two dimensional array in JavaScript?
(56 answers)
Closed 5 years ago.
I am creating a map of array using this:
var m = new Map(Array(40).fill(new Array()).entries());
Now, I want to push values in those array. But when I do this:
m.get(1).push(10)
The value 10 gets pushed into all the arrays instead of the one at 1st position.
You could take another pattern to build independent arrays.
var m = new Map(Array.from({ length: 40 }, _=> []).entries());
m.get(1).push(10);
console.log([...m]);
fill gets single array an uses it to fill all rows of the given array, it doesn't create a new array for each row. This means that your single array reference is shared between all rows. Because array is a reference type, you use the single reference to manipulate it, so the actual object is changed. You can check this by comparing the references of each row.
const arr = new Array(2).fill(new Array());
console.log(arr[0] === arr[1]);
For creating separate arrays, you can see #Nina's answer above

For...of es6 - how about getting index? [duplicate]

This question already has answers here:
How can the current number of i be accessed in a for of loop?
(6 answers)
Closed 6 years ago.
Lets say we have an array "myArray" and we want to iterate over it using the for..of. We are searching for a specific value and when we find it, we want to return the index where the value was. So, i have this:
var myArray=[1,2,3,4,5];
for (let item of myArray) {
if (item===3) {
//return index?
}
}
Is there any way to get the index? Thanks.
It does not come out of the box, but you may employ the new Array.prototype.entries(), which returns an iterator over the index-value pairs:
for (const [index, value] of myArray.entries()) {
// ...
}
Alternatively you could use the new Array.prototype.findIndex() which accepts a predicate and returns an index of the first element that matches it. Eg:
myArray.findIndex(v => v > 10); // would return an index of a first value
// that is greater than 10

Categories

Resources