I have an array like the following
var data = [
["1"," 101_30.1.101_34","0.0200112629","mm/s","[OK]"],
["1"," 101_30.1.101_35","0.0146548533","mm/s","[OK]"],
["1"," 101_30.1.101_45","0.0146548533","mm/s","[OK]"],
["1"," 101_42.2.101_43","0.0101406257","mm/s","[OK]"],
["2"," 102_17.3.102_38","5.1719756","mm/s","[WA]"],
["2"," 102_17.3.102_39","3.5886707","mm/s","[WA]"],
["2"," 102_17.3.102_44","9.4615074E-4","mm/s","[OK]"],
["2"," 102_40.4.102_41","4.8159785","mm/s","[OK]"],
["3"," 204_15","3.8374166","mA","[OK]"],
["4"," 501_11","1027.5156","RPM","[WA]"]
]
What im trying to do is find how many unique array there are. Example 1=4,2=4,3=1,4=1
The data is coming from a database, so the number of arrays can always change.
Here is a simple jsfiddle of what im talking about JsFiddle
Try something like this:
var count = {};
$.each(data, function(){
var num = this[0]; // Get number
count[num] = count[num]+1 || 1; // Increment counter for each value
});
console.log(count); // {1: 4, 2: 4, 3: 1, 4: 1}
Related
Hi I am creating dynamic filter like this
Filter 1
--property 1
--property 2
--property 3
Filter 2
--property 1
--property 2
--property 3
Thats the code
var js_filter = {};
var creators_cat = [];
$('.filter-item input').on('change',function (e) {
var filter_type = $(this).attr('name');
var filter_term = $(this).val();
creators_cat.push( filter_term );
js_filter["'"+filter_type+"'"] = creators_cat;
console.log(js_filter);
})
and that's a response I get
{'filter-product_cat[]': Array(4), 'filter-brands': Array(4)}
'filter-brands': (4) ['32', '29', '23', '36']
'filter-product_cat[]': (4) ['32', '29', '23', '36']
[[Prototype]]: Object
as you can see array keys are dynamically added but values are the same for both of the keys.
An I need to add these separately.
Been looking for answer for quiet some time and didn't find something similar.
Would appreciate any help.
You shouldn't be pushing onto a global array. Each filter input should have its own array of values.
Check if there's already an element of the js_filter object for the current filter_type. If not, create it as an empty array. Then push the current value onto the array.
$('.filter-item input').on('change', function(e) {
var filter_type = $(this).attr('name');
var filter_term = $(this).val();
if (!js_filter[filter_type]) {
js_filter[filter_type] = [];
}
js_filter[filter_type].push(filter_term);
console.log(js_filter);
})
[{…}]
0: {productName: "Powermax 125", travelSpeed: 30, materialThickness: 1, process: "125 Amps"}
length: 1
__proto__: Array(0)
Hello, This is my console output from sorting 18 sets of information like this. I have successfully sorted the list to just the entry above. now I want to store each set of information into its own variable. This is in Javascript
The Variable above is sortedList
Can someone help me make code to pull each bit of information out as a new variable?
I tried
finalProduct = sortedList.productName
finalTravelSpeed = sortedlist.travelSpeed
finalMaterialThickness= sortedList.materialThickness
finalProcess = sortedlist.process
You only make some little typos: you wrote in some cases sortedlist instead of sortedList, you didn't use camelCase-writing and you forgot the ";" and the line-end.
Because your sorted list is an array and you want the first element of it you allways have to take the first element sortedList[0] and not sortedList.
let sortedList= [{productName: "Powermax 125", travelSpeed: 30, materialThickness: 1, process: "125 Amps"}];
finalProduct = sortedList[0].productName;
finalTravelSpeed = sortedList[0].travelSpeed;
finalMaterialThickness= sortedList[0].materialThickness;
finalProcess = sortedList[0].process;
console.log (finalProduct, finalTravelSpeed, finalMaterialThickness, finalProcess);
From what i understood this is an array of objects of length 1, so first you should access index 0 of that array to get that object:
let finalProduct = sortedList[0].productName
let finalTravelSpeed = sortedlist[0].travelSpeed
let finalMaterialThickness= sortedList[0].materialThickness
let finalProcess = sortedlist[0].process
as far as i understood ! you want method to pulling
data from arrays or objects and put this data in dynamic variables have same name
var sortedList= [{productName: "Powermax 125", travelSpeed: 30, materialThickness: 1, process: "125 Amps"}];
// this function for extract objects to variables worked dynamically
function extractor_Object(obj = {}){
for(let i in obj) window[i] = obj[i];
}
extractor_Object(sortedList[0]);
console.log(productName , travelSpeed , materialThickness , process);
i hope this function help you
I'm trying to match and group objects, based on a property on each object, and put them in their own array that I can use to sort later for some selection criteria. The sort method isn't an option for me, because I need to sort for 4 different values of the property.
How can I dynamically create separate arrays for the objects who have a matching property?
For example, I can do this if I know that the form.RatingNumber will be 1, 2, 3, or 4:
var ratingNumOne = [],
ratingNumTwo,
ratingNumThree,
ratingNumFour;
forms.forEach(function(form) {
if (form.RatingNumber === 1){
ratingNumOne.push(form);
} else if (form.RatingNumber === 2){
ratingNumTwo.push(form)
} //and so on...
});
The problem is that the form.RatingNumber property could be any number, so hard-coding 1,2,3,4 will not work.
How can I group the forms dynamically, by each RatingNumber?
try to use reduce function, something like this:
forms.reduce((result, form) => {
result[form.RatingNumber] = result[form.RatingNumber] || []
result[form.RatingNumber].push(form)
}
,{})
the result would be object, with each of the keys is the rating number and the values is the forms with this rating number.
that would be dynamic for any count of rating number
You could use an object and take form.RatingNumber as key.
If you have zero based values without gaps, you could use an array instead of an object.
var ratingNumOne = [],
ratingNumTwo = [],
ratingNumThree = [],
ratingNumFour = [],
ratings = { 1: ratingNumOne, 2: ratingNumTwo, 3: ratingNumThree, 4: ratingNumFour };
// usage
ratings[form.RatingNumber].push(form);
try this its a work arround:
forms.forEach(form => {
if (!window['ratingNumber' + form.RatingNumber]) window['ratingNumber' + form.RatingNumber] = [];
window['ratingNumber' + form.RatingNumber].push(form);
});
this will create the variables automaticly. In the end it will look like this:
ratingNumber1 = [form, form, form];
ratingNumber2 = [form, form];
ratingNumber100 = [form];
but to notice ratingNumber3 (for example) could also be undefined.
Just to have it said, your solution makes no sense but this version works at least.
It does not matter what numbers you are getting with RatingNumber, just use it as index. The result will be an object with the RatingNumber as indexes and an array of object that have that RatingNumber as value.
//example input
var forms = [{RatingNumber:5 }, {RatingNumber:6}, {RatingNumber:78}, {RatingNumber:6}];
var results = {};
$.each(forms, function(i, form){
if(!results[form.RatingNumber])
results[form.RatingNumber]=[];
results[form.RatingNumber].push(form);
});
console.log(results);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
HIH
// Example input data
let forms = [{RatingNumber: 1}, {RatingNumber: 4}, {RatingNumber: 2}, {RatingNumber: 1}],
result = [];
forms.forEach(form => {
result[form.RatingNumber]
? result[form.RatingNumber].push(form)
: result[form.RatingNumber] = [form];
});
// Now `result` have all information. Next can do something else..
let getResult = index => {
let res = result[index] || [];
// Write your code here. For example VVVVV
console.log(`Rating ${index}: ${res.length} count`)
console.log(res)
}
getResult(1)
getResult(2)
getResult(3)
getResult(4)
Try to create an object with the "RatingNumber" as property:
rating = {};
forms.forEach(function(form) {
if( !rating[form.RatingNumber] ){
rating[form.RatingNumber] = []
}
rating[form.RatingNumber].push( form )
})
I need one help. I need to insert one new value into existing array by matching the key value using Javascript.I am explaining the scenario below.
var galArr=[
{'image':'12.png','comment':'hii','act':'edit'},
{'image':'13.png','comment':'hello','act':'edit'},
{'image':'14.png','comment':'hee','act':'edit'},
]
The above is my existing array.I need to match with the below another array.
var arr=[
{'image':'12.png','comment':'hii'},
{'image':'14.png','comment':'hee'},
]
Here i need to match the array arr with an array galArr if image name will same this checked:true will add in the rective row of existing array galArr. Suppose arr[0].image==galArr[0].image then checked:true will add in that respective row of existing array. Please help me.
This should be sufficient.
var galArr=[
{'image':'12.png','comment':'hii','act':'edit'},
{'image':'13.png','comment':'hello','act':'edit'},
{'image':'14.png','comment':'hee','act':'edit'},
];
var arr=[
{'image':'12.png','comment':'hii'},
{'image':'14.png','comment':'hee'},
];
// start looping over `arr`
arr.forEach(function(o, i){
// now loop over `galArr` to find match
galArr.forEach(function(gO, i){
// when there is a match
if(o.image == gO.image){
console.log(gO);
// add checked property to this object
gO['checked'] = true;
}
});
});
// Output
console.log(galArr);
First of all check condition and if the condition match then create a new temp json and replace it with old json
arr.forEach(function(d){
galArr.forEach(function(e){
if(e.image==d.image){
temp = {};
temp.image = e.image;
temp.comment = e.comment;
temp.checked = e.comment;
temp.action = e.action;
e = temp;
}
});
});
I would create an image index, where its indexes would be the whole image file names and later I would use that image index to quickly check and add checked property to galArr array:
var galArr=[
{'image':'12.png','comment':'hii','act':'edit'},
{'image':'13.png','comment':'hello','act':'edit'},
{'image':'14.png','comment':'hee','act':'edit'},
];
var imageIndex = galArr.map(function(item) {
return item.image;
});
var arr=[
{'image':'12.png','comment':'hii'},
{'image':'14.png','comment':'hee'},
]
arr.forEach(function(item) {
item.checked = imageIndex.indexOf(item.image) > -1;
});
If your users will use your JavaScript code within a modern Web browser, I would use the new Set collection:
var galArr=[
{'image':'12.png','comment':'hii','act':'edit'},
{'image':'13.png','comment':'hello','act':'edit'},
{'image':'14.png','comment':'hee','act':'edit'},
];
var imageIndex = galArr.reduce(function(result, item) {
result.add(item.image);
return result;
}, new Set());
var arr=[
{'image':'12.png','comment':'hii'},
{'image':'14.png','comment':'hee'},
]
arr.forEach(function(item) {
item.checked = imageIndex.has(item.image);
});
I've asked a question to assist everyone in understanding how valueable are sets: Is Set a hashed collection in JavaScript?
I need one help.I have some array of data i need to sort the as per key value and measure the length.I am explaining my code below.
var response = [{
day_id:1,
day_name:"Monday",
subcat_id:"2",
cat_id:"1",
comment:"hii"
}, {
day_id:1,
day_name:"Monday",
subcat_id:"1",
cat_id:"2",
comment:"hello"
}
{
day_id:2,
day_name:"Tuesday",
subcat_id:"3",
cat_id:"2",
comment:"hii"
}]
Here for day_id=1 there are two set of data and same for day_id=2 present.I need to measure length of data set present as per day_id e,g.for day_id=1 length is 2Please help me.
You can map response and save in an object how many times each id was seen:
var counter = {};
response.map(function(item) {
counter[item.day_id] = (counter[item.day_id] || 0) + 1;
});
Your results are in counter:
console.log(counter);
// { '1': 2, '2': 1 }
Hope it helps.
Do not use .map, use .forEach as it doesn't return another array
and the code could be a little cleaner:
var counter = {};
response.forEach(function(item) {
counter[item.day_id] = ++counter[item.day_id] || 1;
});