I have an array which looks like this:
["1,8", "4,6,8", "8,9", "6,9"]
1/ I would like to turn it in to this
[1,8,4,6,8,8,9,6,9]
2/ I would then like to find matching values, by looking for the most number:
[8]
This first has been solved with this:
var carArray = ["1,8", "4,6,8,7,7,7,7", "8,9", "6,9"];
//1) create single array
var arr = carArray.join().split(',');
//2) find most occurring
var counts = {}; //object to hold count for each occurence
var max = 0, maxOccurring;
arr.forEach(function(el){
var cnt = (counts[el] || 0); //previous count
counts[el] = ++cnt;
if(cnt > max && cnt > 1){ //only register if more than once (cnt>1)
max=cnt;
maxOccurring = el;
}
});
if(maxOccurring){
//there was an element more than once, maxOccuring contains that element
setResult('Most occuring: ' + maxOccurring + ' (' + max + ' times)');
}
else{
//3)/4) ???
setResult('sorting?');
}
//below is only for test display purposes
function setResult(res){
console.log(res);
}
3/ If the are no matching values like this
[1,8,4,6,5,7]
4/ Then I need to compare this array to another array, such as this
[6,7,4,1,2,8,9,5]
If the first number in <4> array above appears in <3> array, then get that number, ie in the above example I need to get 6. The <4> array will be static values and not change. The numbers is <3> will be dynamic.
EDIT Not the most elegant of answers, but I do have something working now. I didn't compare the original array directly with the second array, instead used simple if/else statements to do what I needed:
var carArray = ["1,5", "4", "8,2", "3,9,1,1,1"];
//1) create single array
var arr = carArray.join().split(',');
//2) find most occurring
var counts = {}; //object to hold count for each occurence
var max = 0, maxOccurring;
arr.forEach(function(el){
var cnt = (counts[el] || 0); //previous count
counts[el] = ++cnt;
if(cnt > max && cnt > 1){ //only register if more than once (cnt>1)
max=cnt;
maxOccurring = el;
}
});
if(maxOccurring){
//there was an element more than once, maxOccuring contains that element
console.log('Most occuring: ' + maxOccurring + ' (' + max + ' times)');
console.log(maxOccurring);
}
else {
// If not occuring, match from a list
if(jQuery.inArray("6", arr) !== -1) { console.log('6'); }
else if(jQuery.inArray("9", arr) !== -1) { console.log('9'); }
else if(jQuery.inArray("7", arr) !== -1) { console.log('7'); }
else if(jQuery.inArray("5", arr) !== -1) { console.log('5'); }
else if(jQuery.inArray("4", arr) !== -1) { console.log('4'); }
else if(jQuery.inArray("1", arr) !== -1) { console.log('1'); }
else { console.log('not found'); }
}
Example Fiddle
Step 1 is fairly easy by using javascript's join and split methods respectively:
var arr = carArray .join().split(',');
For step 2, several methods can be used, the most common one using an object and using the elements themselves as properties. Since you only need to get the most occurring value if there is a reoccurring value, it can be used in the same loop:
var counts = {}; //object to hold count for each occurence
var max = 0, maxOccurring;
arr.forEach(function(el){
var cnt = (counts[el] || 0); //previous count
counts[el] = ++cnt;
if(cnt > max && cnt > 1){ //only register if more than once (cnt>1)
max=cnt;
maxOccurring = el;
}
});
After the above, the variable maxOccurring will contain the reoccurring value (if any) and max will contain the times it occured
For step 4 the easiest way is to loop through the compare array and get the element that occurs in the input array:
var cmpArr = ['6','7','4','1','2','8','9','5'];
//find the first occurrence inside the cmpArr
res = function(){ for(var i= 0 ; i < cmpArr.length; i++){ if(arr.indexOf(cmpArr[i]) !== -1)return cmpArr[i];}}();
The above uses an in place function which is called immediately to be able to use return. You could also just use a loop and assign res when found, then break from the loop.
Last update, an alternate fiddle where the above is converted to a single function: http://jsfiddle.net/v9hhsdny/5/
Well first of all the following code results in four matching answers since the jQuery selectors are the same.
var questionAnswer1 = $(this).find('input[name=questionText]').val();
var questionAnswer2 = $(this).find('input[name=questionText]').val();
var questionAnswer3 = $(this).find('input[name=questionText]').val();
var questionAnswer4 = $(this).find('input[name=questionText]').val();
var carArray = [questionAnswer1, questionAnswer2, questionAnswer3, questionAnswer4];
You could use the eq(index) method of jQuery to select the appropriate element. However having 4 inputs with the same name is a bad practice.
Well lets say that the carArray has 4 different values which all consist out of comma separated numbers. You could then do the following:
var newArr = [];
carArray.forEach(function(e) {
e.split(",").forEach(function(n) {
newArr.push(n);
});
});
Well then we got to find the most occurring number. JavaScript doesn't have any functions for that so we will have to find an algorithm for that. I found the following algorithm on this stackoverflow page
var count = function(ary, classifier) {
return ary.reduce(function(counter, item) {
var p = (classifier || String)(item);
counter[p] = counter.hasOwnProperty(p) ? counter[p] + 1 : 1;
return counter;
}, {})
}
var occurances = count(newArr);
It isn't clear to me what you're trying to do in step 3 and 4, so can't answer those at the moment.
var ary = ["1,8", "4,6,8", "8,9", "6,9"];
var splitted = ary.reduce(function(acc, item) {
return acc.concat(item.split(','));
}, []);
var occurences = splitted.reduce(function(acc, item) {
if (!acc.hasOwnProperty(item)) acc[item] = 0;
acc[item] += 1;
return acc;
},{}),
biggest = Object.keys(occurences).reduce(function (acc, key) {
if (occurences[key] > acc.occurences) {
acc.name = key;
acc.occurences = occurences[key];
}
return acc;
},{'name':'none','occurences':0}).name;
var vals=["1,8", "4,6,8", "8,9", "6,9"];
// 1) turn into number array
var arrNew=[];
for(var i=0; i<vals.length; i++)
{
arrLine=vals[i].split(",");
for (var j=0;j<arrLine.length;j++) { arrNew.push (parseInt(arrLine[j])) }
}
//result:
alert(arrNew.join(";");
// 2) find most common
var found=[];
for(var i=0; i<arrNew.length; i++) {
// make an array of the number of occurrances of each value
if (found["num"+newArray[i]]) {
found["num"+newArray[i]] ++ ;
} else {
found["num"+newArray[i]]=1;
}
}
var mostCommon={count:0,val:"ROGUE"};
for (x in found) {
if (found[x] > mostCommon.count) {
mostCommon.count=found[x].count;
mostCommon.val=x;
}
}
// result :
alert(mostCommon.val);
//3) not quite sure what you meant there
// 4) unique values:
// at this point the 'found' list contains unique vals
var arrUnique=[];
for (x in found) {
arrUnique.push[x];
}
// result :
alert(arrUnique.join(";"))
//sort:
arrUnique.sort(function(a, b){return a-b});
(This won't work in most browsers) but on a side note, when ES6 becomes widely supported, your solution could look like this:
var arr1 = ["1,8", "4,6,8", "8,9", "6,9"];
var arr2 = arr1.join().split(',');
var s = Array.from(new Set(arr2)); //Array populated by unique values, ["1", "8", "4", "6", "9"]
Thought you might like to see a glimpse of the future!
1.
var orgArray = ['1,8', '4,6,8', '8,9', '6,9'];
var newArray = [];
for (var i in orgArray) {
var tmpArray = orgArray[i].split(',');
for (var j in tmpArray) {
newArray.push(Number(tmpArray[j]));
}
}
2.
var counts = {};
var most = null;
for (var i in newArray) {
var num = newArray[i];
if (typeof counts[num] === 'undefined') {
counts[num] = 1;
} else {
++(counts[num]);
}
if (most == null || counts[num] > counts[most]) {
most = num;
} else if (most != null && counts[num] === counts[most]) {
most = null;
}
}
I don't understand the question 3 and 4 (what "unique order" means) so I can't answer those questions.
I have array which holds option values from select.
var arrValues = new Array();
$("#myId option").each(function()
{
var sel = $("#myId").val();
arrValues.push(sel);
}
now I want to find current selected value from #myId select option and take next array index value.
forexample
if array contains values like
array = "AB", "CD", "EF"
if my currently selected value is AB I want to take CD value and store into var nextValue variable.
This is how you would do it:
D E M O
var curval, nextval, _index, arrValues = new Array();
$(function() { bindDropdown();});
function bindDropdown() {
$("#myselect option").each(function()
{
arrValues.push($(this).val());
});
$("#myselect").on('change', function() {
curval = $( "#myselect" ).val();
_index = $.inArray(curval, arrValues);
nextval = arrValues[(_index==arrValues.length-1) ? 0 : _index+1];
});
}
nextval will be your next value..
Notice: if you choose the last option, then your next becomes the first.. I don't know if that's your desired behavior so let me know..
following function returns the next value or an empty string if the current value is the last value:
function getNextValue(array, currentValue) {
var nextValue = "";
for(var i = 0; i < array.length - 1; i++) {
if(array[i] == currentValue) {
nextValue = array[i + 1];
break;
}
}
return nextValue;
}
You can use Array.prototype.indexOf to find the index in the array, then just increment it to get the next. Be careful if the last option is selected, because there is no next value.
var nextValue;
var index = arrValues.indexOf($('#myId').val());
if(index < arrValues.length-1){
nextValue = arrValues[index+1];
} else {
// the selected value is the last in the array so can't get next
}
I'm looping through all classnames in my html body.
I'd like to store the classname with textSize value. Each time there is a duplicate value for a given classname, I want to increment its textSize.
$("*").each(function() {
classname = $(this).get(0).className;
myarray.push({"className" : classname, "textSize" : 5});
Here, I attempt to sort the classnames, then get a count for each duplicate:
myarray.sort();
var current = null;
var dupCount = 0;
for (var i = 0; i < myarray.length-1; i++) {
if (myarray[i]["className"] !== "") {
if (myarray.indexOf(myarray[i]["className"]) == -1) {
log(myarray[i]["className"]);
}
else {
log("DUP");
myarray[i]["textSize"] = myarray[i]["textSize"] += 5;
dupCount++;
}
}
}
log(myarray[i]["className"]);, shown in the image below, clearly shows duplicates:
Yet, log("DUP"); is never called once. Why is that?
Moreover, why doesn't myarray.sort(); sort them alphabetically? If it did that, I could just do if (myarray[i]["className"] === myarray[i++]["className"]) { to check if the value equals the next value in the array. But sort doesn't work.
Edit:
So when looping through, I should be able to alter the css per classname, right?
for(var classname in classes) {
console.log(classes[classname].textSize);
var $val = $(classes[classname]);
$val.css({
"color" : "blue",
"fontSize": $val.textSize+"px"
});
}
This doesn't work even though console.log(classes[classname].textSize); gives text sizes per element
Try using an object instead of an array, using class names as the keys:
var classes = {};
$("*").each(function() {
var classname = $(this).get(0).className;
var c = classes[classname] ||
(classes[classname] = { className: classname, textSize: 0 });
c.textSize += 5;
});
for(var classname in classes) {
console.log(classes[classname]);
}
Remember that any element can have multiple classes. If you want to account for that, you'll have to split up the class names:
$("*").each(function() {
var classnames = $(this).get(0).className.split(' ');
for(var i=0; i<classnames.length; i++) {
var classname = classnames[i];
var c = classes[classname] ||
(classes[classname] = { className: classname, textSize: 0 });
c.textSize += 5;
}
});
See this demonstration: http://jsfiddle.net/FSBhv/
UPDATE: the OP clarified that he wants to set the text size on the elements based on the number of elements that have that class. Doing that will take a slightly different approach (we'll actually have to store the elements):
var eltsByClass = {};
$("*").each(function() {
var $this = $(this);
$this.get(0).className.split(' ').forEach(function(cname) {
var c = eltsByClass[cname] ||
(eltsByClass[cname] = []);
c.push($this.get(0));
});
});
for(var cname in eltsByClass) {
var elts = eltsByClass[cname];
$(elts).css('font-size', (elts.length + 1) * 5 + 'px');
}
Store your data in an object, not an Array. And it can be simplified as:
var classes = {};
$("*").each(function() {
var classname = $(this).get(0).className;
classes[classname] = (classes[classname] || 0) + 5;
});
for(var classname in classes) {
console.log(classname + " textSize:" + classes[classname]);
}
myarray.indexOf(myarray[i]["className"]) is a problem.
You know that myarray contains only objects, but you're asking for the position of a string within that list. That's never going to return anything but -1.
Consider using a second array to store the frequency count, instead of trying to do both with myarray.
var frequency = {};
myarray.forEach(function (i) {
frequency[i.className] = frequency[i.className] || 0
frequency[i.className]++;
}
This will hely you to sort array alphabetically based on classname
var myarray=[];
$("*").each(function()
{
classname = $(this).get(0).className;
myarray.push({"className" : classname, "textSize" : 5});
});
function compare(a,b)
{
if (a.className < b.className)
return -1;
if (a.className > b.className)
return 1;
return 0;
}
myarray.sort(compare);
i got a group of inputs... each one has a number value.
i want to get all their values (found a method here) and then compare
then and highlight the heighest input meaning highlight the input itself
meaning i need to somehow grab its id and know which one i am comparing to...
(i hope i explained it good).
This is what i have for now taken from the link attached:
var values = [];
$("input[name='items[]']").each(function() {
values.push($(this).val());
});
try something like this
$(function(){
var higesht_val = 0;
var higesht_val_id = 0;
$("input[name='items[]']").each(function() {
var current_val = parseInt(this.value);
if(higesht_val < current_val){
higesht_val = current_val;
higesht_val_id = this.id;
}
});
alert(higesht_val); // highest value
alert(higesht_val_id);// id of highest value input
})
var highestVal = 0,
$target;
$("input[name='items[]']").each(function() {
if(parseInt($(this).val()) > highestVal){
highestVal = parseInt($(this).val());
$target = $(this);
}
});
// $target is now the input with the highest value
how about this ?
var values = [];
$("input[name='items[]']").each(function() {values.push(this);});
values.sort(function(a, b){return b.value - a.value;})
highlight(values[0]);
I have an array called tmp
var tmp = ["05", "13", "27"];
if an option value is equal to a value within tmp, I want to add that option to a particular optgroup, else add it to the other optgroup. I keep getting everything added to optgroup #2, except the option with the value "27". What am I doing incorrectly?
var groups = $("optgroup");
$("option").each(function() {
var value = $(this).val();
for (var x = 0; x < tmp.length; x++) {
var isMatch = (tmp[x] === value);
if (isMatch) {
$(this).appendTo($(groups[0]));
} else if (value.length > 0) {
$(this).appendTo($(groups[1]));
}
}
});
Thanks for any pointers to correct this.
~ck in San Diego
You should add a break after each appendTo statement so that you don't keep comparing the option to all tmp values.
var groups = $("optgroup");
$("option").each(function() {
var value = $(this).val();
for (var x = 0; x < tmp.length; x++) {
var isMatch = (tmp[x] === value);
if (isMatch) {
$(this).appendTo($(groups[0]));
break;
} else if (value.length > 0) {
$(this).appendTo($(groups[1]));
break;
}
}
});
Firstly,
$(this).appendTo($(groups[1]));
can be changed to
$(this).appendTo(groups[1]);
you don't need to wrap the element again into a jQuery object in order to append to it, a HTMLElement will work fine.
Do you have the HTML that you're using and where are your <option> elements that you are checking the value of?
EDIT:
I've rewritten your code slightly and this works correctly (N.B. appending won't work in IE6 and I believe 7 and 8 too - In IE the innerHTML property for a select element is readonly, so use createElement or the Option constructor to create options),
Working Example. add /edit to the URL to see the code. I have the option elements in an array in the working example, I assume that you have them in a similar structure.
var groups = $("optgroup");
$('options').each(function() {
var $this = $(this);
var val = $this.val();
if (tmp.indexOf(val) !== -1) {
$this.appendTo(groups[0]);
}
else if (val.length > 0) {
$this.appendTo(groups[1]);
}
});