Count occurrences of array elements with JavaScript [duplicate] - javascript

This question already has answers here:
How to count duplicate value in an array in javascript
(35 answers)
Closed 7 years ago.
I have this JavaScript array with length 129.
var fullnames = [Karri, Ismo, Grigori, Ahmed, Roope, Arto .....]
I would like to find how many times those names appeared in an array and store that information in an array like this:
var counter = [2, 5, 7, ..]
where Karri occured in fullnames array 2 times, Ismo occured 5 times etc. Any ideas about how to do it?

This is the best - and simple - way I can think of:
var fullnames = ["Karri", "Ismo", "Grigori", "Ahmed", "Roope", "Ahmed", "Karri", "Arto", "Ahmed"];
var counts = {};
for (var i = 0; i < fullnames.length; i++)
{
if (!counts.hasOwnProperty(fullnames[i]))
{
counts[fullnames[i]] = 1;
}
else
{
counts[fullnames[i]]++;
}
}
console.log(counts);
Original Fiddle.
Using an array to store the counts doesn't makes much sense, so I used an object instead.

I am assuming that fullnames is array of strings. If so, you can do it like so:
var occurences = { };
for (var i = 0; i < fullnames.length; i++) {
if (typeof occurences[fullnames[i]] == "undefined") {
occurences[fullnames[i]] = 1;
} else {
occurences[fullnames[i]]++;
}
}
console.log(occurences); // Prints out something like: {"Karri": 2, "Ismo": 5, ...}

var fullnames = ['Karri', 'Ismo', 'Grigori', 'Karri', 'Ismo', 'Grigori', 'Grigori', 'Karri', 'Ismo', 'Grigori', 'Grigori'];
var counts = [];
fullnames.forEach(function(_item) {
if(typeof counts[_item] === 'undefined') counts[_item] = 1;
else counts[_item]++;
});
var result = [];
for(i in counts) result.push(counts[i]);
console.log(result);
// outputs [3, 3, 5]

Related

Check if element is in array twice time [duplicate]

This question already has answers here:
Finding out how many times an array element appears
(6 answers)
Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array
(97 answers)
Closed 6 years ago.
I need to know if an element is in array twice or many time.
var arr = [elm1,elm2,elm3,elm3,elm4,elm5,elm5,elm5,elm6,elm7] ;
if(elm is in array by many time ){
// do some code with this element
}else{
// other stuff ;;
}
Any suggestions ?
The countInArray function may be an option for you
function countInArray(array, what) {
return array.filter(item => item == what).length;
}
Or something like this, this may be better for you to understand the code and adjust somethings where you want to! :
var list = [2, 1, 4, 2, 1, 1, 4, 5];
function countInArray(array, what) {
var count = 0;
for (var i = 0; i < array.length; i++) {
if (array[i] === what) {
count++;
}
}
return count;
}
countInArray(list, 2); // returns 2
countInArray(list, 1); // returns 3
function check(){
var arr =['1','2','3','3','4'];
for (i=0; i<arr.length;i++){
for (x=0;x<arr.length;x++){
if(arr[i]==arr[x] && i != x){
console.log('SAME ones in ARRAY: '+arr[i]);
}else console.log('no same ones');
}
}
}

Javascript: Write a function that takes in an array, and then returns an array with only unique numbers, only arrays removed

Write a function that takes in a list and returns a list with all of the duplicates removed (list will only have unique numbers).
Here's what I have so far:
var lista = [1,4,5,1,1,3,5,6,4,4,3];
function dupRemove (lista) {
//Sort the array in case it isn't sorted
lista.sort();
//Object to store duplicates and unique numbers
var listNumbers = {
"Duplicate Numbers": [],
"Unique Numbers": []
};
for (var i = 0; i < lista.length; i++) {
//check if it is not equal to the index of the array before it and after. if it isn't, that means its unique, push it in the uniques array.
if (lista[i] !== lista[i-1] && lista[i] !== lista[i+1]) {
listNumbers["Unique Numbers"].push(lista[i]);
} else {
listNumbers["Duplicate Numbers"].push(lista[i]);
}
}
return listNumbers;
}
Currently, my solution returns an object with keys with the values of "Duplicates": 1, 1, 1, 3, 3, 4, 4, 4, 5, 5 and "Uniques": 6.
How do I remove the duplicates from duplicates and then join these two keys into a single array?
Thank you.
that answer is seriously over -engineered- all you need to to is push all values into a new array if they are not already in it.
function=removeDups()
{
var lista = [1,4,5,1,1,3,5,6,4,4,3];
var uniqueValues=[];
var duplicateValues=[];
for(i=0;i<lista.length;i++)
{
if(uniqueValues.indexof(lista[i] == -1){uniqueValues.push(lista[i]}else{duplicateValues.push(lista[i]}
}
}
You could just use the default filter method that is on all Arrays
You don't need the sort function either. If the item is already found using the indexOf method it will not be added to the newly returned array created by the filter method
var list = [1,4,5,1,1,3,5,6,4,4,3];
function removeDup (arr) {
return arr.filter(function(item, pos) {
return arr.indexOf(item) == pos;
})
}
var sortedList = removeDup(list).sort(function(a,b){
return a - b
})
document.getElementsByTagName('div')[0].textContent = sortedList
<div></div>
Kind of a non elegant solution but it gives you the two arrays: one with the duplicate values and one with the unique ones. Since you cannot rely on .sort() you can just count things.
Function checkList will give you back those two arrays.
var list = [1,4,5,1,1,3,5,6,4,4,3];
console.log(checkList(list));
function checkList(list) {
var uniques = []; // will be [6]
var dups = []; // will be [1, 4, 5, 3]
var checked = []; // save what you have already checked so far
for(i = 0; i < list.length; i++) {
if(notChecked(list[i], checked)) {
checked.push(list[i]);
if(count(list[i], list) > 1) {
dups.push(list[i]);
} else {
uniques.push(list[i]);
}
}
}
return {dups: dups, uniques: uniques}
}
// count how many num in arr
function count(num, arr) {
var count = 0;
var i;
for(i = 0; i < arr.length; i++) {
if(arr[i] == num) count++;
if(count > 1) return count;
}
return count;
}
// check if num has not been checked
function notChecked(num, arr) {
return (arr.indexOf(num) == -1) ? true : false;
}

Looping through array and get the same value only once [duplicate]

This question already has answers here:
How to get unique values in an array [duplicate]
(20 answers)
Closed 6 years ago.
I have an array
var myArray = ['1','1','2','2','1','3'] // 6 item
Is there any ways I can return the value of 1 and 2 and 3 ONE time when looping?
//example in pseudocode
var getNumber = [];
var count = 0;
var check = 0;
for(var i in myArray)
{
if(getNumber[check] !== myArray[i])
{
getNumber[count] = myArray[i];
count++;
}
else
{
}
}
and advice to follow up my previous code?
thanks
You should use Array.indexOf and Array.push to check and insert values.
var getNumber = [];
for(var i in myArray)
{
if(getNumber.indexOf(myArray[i]) < 0) //See if the number wasn't found already
{
getNumber.push(myArray[i]);
}
else
{
//This number was found before. Do nothing!
}
}
you could do something like :
function leaveDupes(arry){
var newArry = [], keys={};
for(var i in arry){
if(!keys[arry[i]]){
newArry.push(arry[i]);
keys[arry[i]]=true;
}
}
return newArry;
}
console.log(leaveDupes(['1','1','2','2','1','3'] ))
using underscore.js, you can do something like:
newArry = _.uniq(['1','1','2','2','1','3']);
var obj = {};
for (var i = 0; i < myArray.length; i++) {
if (!obj[myArray[i]]) {
obj[myArray[i]] = true;
console.log(myArray[i]); //these are the unique values
}
}
This will work.
var myArray = ['1','1','2','2','1','3']
var getNumber = {};
var retArray = [];
myArray.forEach(function(val){
if(!getNumber[val]){
getNumber[val] = val;
retArray.push(val);
}
});
return retArray
You can use forEach and indexOf array method to find the unique elements.
var myArray = ['1','1','2','2','1','3','4','4','5'];
var uniqueArray =[]; //A new array which will hold unique values
function _unique(myArray){
myArray.forEach(function(item,index){
if(uniqueArray.indexOf(item) ==-1){ //Check if new array contains item
uniqueArray.push(item)
}
})
}
_unique(myArray);

how to get diff btw two arrays in javascript? [duplicate]

This question already has answers here:
How to find elements in array2 that are not in array1?
(2 answers)
Closed 8 years ago.
I have a array a=[1,2,3,4,5] b=[3,4,5,6,7]
Here i want values of array a [1,2] and array b [6,7] and stored in diff arrays like below.
c=[1,2]
d=[6,7]
Thanks in Advance.
its like a=[chkbx_705_49,chkbx_706_49,chkbx_707_49,chkbx_708_49,chkbx_709_49,chkbx_710_49,chkbx_711_49,chkbx_712_49,chkbx_714_49,chkbx_705_50,chkbx_706_50,chkbx_707_50,chkbx_708_50,chkbx_709_50,chkbx_710_50,chkbx_711_50,chkbx_705_51,chkbx_706_51,chkbx_707_51,chkbx_708_51,chkbx_711_51,chkbx_710_52,chkbx_711_52,chkbx_710_53,chkbx_711_53]
b= [chkbx_705_49,chkbx_705_50,chkbx_705_51,chkbx_705_52,chkbx_705_53,chkbx_706_49,chkbx_706_50,chkbx_706_51,chkbx_706_52,chkbx_706_53,chkbx_707_49,chkbx_707_50,chkbx_707_51,chkbx_708_49,chkbx_708_50,chkbx_708_51,chkbx_709_49,chkbx_709_50,chkbx_710_49,chkbx_710_50,chkbx_711_49,chkbx_711_50,chkbx_711_51,chkbx_712_49]
here i deleted chkbx_710_52,chkbx_711_52,chkbx_710_53,chkbx_711_53 checkbox values from array a
and added chkbx_705_52,chkbx_705_53,,chkbx_706_52,chkbx_706_53 added in array b.
So i want c = chkbx_710_52,chkbx_711_52,chkbx_710_53,chkbx_711_53
d = chkbx_705_52,chkbx_705_53,,chkbx_706_52,chkbx_706_53
When a member of A also exists in B, delete in both:
var a = [1,2,3,4,5];
var b = [3,4,5,6,7];
var c = a.slice();
var d = b.slice();
var len = c.length;
while(len--) {
var idx = d.indexOf(c[len]);
if (idx > -1) {
c.splice(len, 1);
d.splice(idx, 1);
}
}
However, you didn't say whether there are duplicated members, so I assume no and do it in the simplest way, just to give you a thought of solution.
You can get it like below:
var array1 = [1,2,3,4,5];
var array2 = [3,4,5,6,7];
var foo1 = [], foo2=[];
var i = 0;
jQuery.grep(array1, function(el) {
if (jQuery.inArray(el, array2) == -1) foo1.push(el);
i++;
});
jQuery.grep(array2, function(el) {
if (jQuery.inArray(el, array1) == -1) foo2.push(el);
i++;
});
alert(" the difference is " + foo1);
alert(" the difference is " + foo2);

How to search an array in Jquery like SQL LIKE value% statement [duplicate]

This question already has answers here:
How to check if a string "StartsWith" another string?
(18 answers)
Closed 9 years ago.
I have an array with some values. How can I search that array using jQuery for a value which is matched or close to it?
var a = ["foo","fool","cool","god","acl"];
If I want to search for c, then it should return cool but not acl.
How I can achieve that?
Try this:-
arr = jQuery.grep(a, function (value) {
search = /c/gi;
if(value.match(search)) return true;
return false;
});
or
function find(arr) {
var result = [];
for (var i in arr) {
if (arr[i].match(/c/)) {
result.push(arr[i]);
}
}
return result;
}
window.onload = function() {
console.log(find(["foo","fool","cool","god","acl"]));
};
Use substring to check if each string in the array begins with the string you are searching for:
var strings = [ "foo", "cool", "acl" ];
var needle = "c";
for (var i = 0; i < strings.length; ++i) {
if (strings[i].substring(0, needle.length) === needle) {
alert("found: " + strings[i]);
}
}
A simple way to do it is to check for words starting with 'c' and iterate of the array.
var ar = ['acl','cool','cat']
for(var i = 0 ; i<ar.length ; i++){
console.log(ar[i].match(/^c/))
}
//Prints:
//null
//["c", index: 0, input: "cool"]
//["c", index: 0, input: "cat"]
You can use the filter method which is available since JavaScript 1.6. It will give you back an array with the filtered values. Very handy if you want to match multiple items.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
var a = ["foo","fool","cool","god","acl"];
var startsWith = 'c';
a.filter(function (value) {
return value && value.length > 0 && value[0] == startsWith;
});
// yields: ["cool"]
var a = ["foo","fool","cool","god","acl"];
var Character="f";
for(i=0;i<a.length;i++){
if(a[i].indexOf(Character)!=-1){
document.write(a[i]+"<br/>");
}
}

Categories

Resources