count occurence of elements in an array [duplicate] - javascript

This question already has answers here:
Counting the occurrences / frequency of array elements
(39 answers)
Closed 4 years ago.
Hello I want to ask how to find same number or string on array
The output must be a number or string
Example
var arr = [1,2,4,4,5,1,1,1,8,9]
Do we need to use loop , function?

You can create a frequency array. Admittedly this might not be the most efficient way.
You can use dictionaries for this. I hope you know what dictionaries are.
function fun(arr) {
var sval;
var dict = new Object();
for (var val in arr) {
sval = string(val)
if(dict[sval] === undefined) {
dict[sval] = 1;
}
else {
dict[sval]++;
}
}
var max_count = -5;
var max_count_num;
for (var key in dict) {
if (max_count < dict[key]) {
max_count = dict[key];
max_count_num = Number(key);
}
}
}
First you create an Object, which is for our purposes serves as a dictionary, then you iterate through the array. If the key is not found, hence undefined, then we create such entry, else we increment the value which is the count by 1.
We then loop through the dictionary trying to find the number with the maximum value, hence the maximum count.
I hope this is what you are looking for.
Please fix any errors in my code, I'm a bit rusty on JavaScript.

Iterate for each item on the array (i index), and iterate for each item for the rest of the array (j index, j = i+1), and create a count to any repetition of current item.
function maxRepeated(arr) {
// count global to keep the max value count
const maxRepeat = {
value: 0,
times: 0
};
for (var i = 0; i < arr.length - 1; i++) {
var maxLocal = 1; // to count ar[i] item repetitions
for (var j = i + 1; j < arr.length; j++) {
if (arr[j] == arr[i]) maxLocal++;
console.log( maxLocal )
console.log( "I " + i + " arr[i] " + arr[i] )
}
// check if maxLocal is great than max global
if (maxLocal > maxRepeat.times) {
maxRepeat.value = arr[i];
maxRepeat.times = maxLocal;
}
}
return maxRepeat;
}
const ar = [1, 2, 3, 1, 3, 5, 1, 1, 1, 5, 4, 3, 3, 2, 2, 3];
const b = ["LUNA", "LUNA", "JS", "JS", "JS"];
//console.log(maxRepeated(ar))
console.log(maxRepeated(b))

Related

remove specified value from array [duplicate]

This question already has answers here:
How can I remove a specific item from an array in JavaScript?
(142 answers)
Closed 1 year ago.
How can I check whether an array contains a value, and if so, remove it?
PS: For this exercise, I'm not allowed to use anything more than than .pop, .push and .length array functions.
My logic is the following: if the specified value is within the array, reorder the array so that the last element of it will contain this value, then remove it with .pop. But how can I find this value and reorder it without using anything more than those array functions I specified above?
This is what I managed to come up with so far:
let array_1 = [1,2,3];
if (array_1 == 2){
//reorder somehow
array_1.pop();
}
console.log(array_1);
Using this approach, you are not creating a new array but modifying it. It uses .pop().
let array_1 = [1, 2, 3];
// Iterate all array
for (let i = 0; i < array_1.length; i++) {
// While there is a 2 element in the actual index, move all elements (from i index) to the previous index
while(array_1[i] === 2) {
for (let j = i; j < array_1.length - 1; j++) {
array_1[j] = array_1[j + 1];
}
// Now remove the last element (since we move all elements to the previous index)
array_1.pop();
}
}
console.log(array_1);
Here a snippet so you can try it
let array_1 = [1, 2, 3, 4, 2, 5, 2, 6, 2];
for (let i = 0; i < array_1.length; i++) {
while(array_1[i] === 2) {
for (let j = i; j < array_1.length - 1; j++) {
array_1[j] = array_1[j + 1];
}
array_1.pop();
}
}
console.log(array_1);
This would mantain the order of the array, but without the "2" elements.
Here's another option using pop
const filter = (array, target) => {
const newArray = [];
let tmp;
while(tmp = array.pop()) {
if (tmp !== target) {
newArray.push(tmp)
}
}
console.log(newArray)
return newArray;
}
filter([1,2,3,4], 2) // [4, 3, 1] Note that it reversed the order of the array!
If you are limited to pop, push and length, you can loop over all elements, check if a given element matches the value you are looking for, and add them to a new array using push.
let array_1 = [1,2,3];
let newArray = [];
for (let i = 0; i < array_1.length; i++) {
if (array_1[i] !== 2) {
newArray.push(array_1[i]);
}
}
console.log(newArray);
// using splice
// splice(indexStart, how many, replace with)
// example :
let arr = [0,1,2,3,4,5];
// remove at index 1
arr.splice(1,1);
console.log( arr );
// replace at index 1
arr.splice(1,1,"new 1");
console.log( arr );
// merge index 2 and 3
arr.splice(2,2,"merge 2 and 3");
console.log( arr );
// create 2 new items start at index 2
arr.splice(2,2,"new 2", "new 3");
console.log( arr );

Get elements that has no double value in an array

I have a question . How do you retrieve elements that has no double value in an array?? For example: [1,1,2,2,3,4,4,5] then you retrieve [3,5] only.
Thanks in advance
for (var j = 0; j < newArr.length; j++) {
if ((arr1.indexOf(newArr[j]) === 0) && (arr2.indexOf(newArr[j]) === 0)) {
index = newArr.indexOf(j); newArr.splice(index, 1);
}
}
If the item in the array is unique then the index found from the beginning should equal the index found from the end, in other words:
var xs = [1, 1, 2, 2, 3, 4, 4, 5];
var result = xs.filter(function(x) {
return xs.indexOf(x) === xs.lastIndexOf(x);
});
console.log(result); //=> [3, 5]
sorry for the presentation its my first post !
You have to compare each element of your array to the others in order to get the number of occurence of each element
var tab = [1,1,2,2,3,4,4,5] //The array to analyze
tab = tab.sort(); // we sort the array
show(tab); // we display the array to the console (F12 to open it)
var uniqueElementTab = []; // this array will contain all single occurence
var sameElementCounter = 0;
for(x=0;x<tab.length;x++){ // for all element in the array
sameElementCounter = 0;
for(y=0;y<tab.length;y++){ // we compare it to the others
if((tab[x]==tab[y])){
sameElementCounter+=1; // +1 each time we meet the element elsewhere
}
}
if(sameElementCounter<=1){
uniqueElementTab.push(tab[x]); //if the element is unique we add it to a new array
}
}
show(uniqueElementTab); // display result
function show(tab) { // Simple function to display the content of an array
var st="";
for(i=0;i<tab.length;i++){
st += tab[i]+" ";
}
console.log(st+"\n");
}
Hope it helps.
Here is a simple "tricky" solution using Array.sort, Array.join, Array.map, String.replace and String.split functions:
var arr = [1, 1, 2, 2, 3, 4, 4, 5];
arr.sort();
var unique = arr.join("").replace(/(\d)\1+/g, "").split("").map(Number);
console.log(unique); // [3, 5]
create new array tmp,and check already value exist by indexOf .If existed delete by splice function..
var arr = [1,1,2,2,3,4,4,5];
var tmp = [];
var dup = [];
for(var i = 0; i < arr.length; i++){
var ind = tmp.indexOf(arr[i]);
if(ind == -1){
if(dup.indexOf(arr[i]) == -1){
tmp.push(arr[i]);
}
}
else{
tmp.splice(ind,1);
dup.push(arr[i]);
}
}
console.log(tmp);
This would be my way of doing this job.
var arr = [1,1,2,2,3,4,4,5],
uniques = Object.keys(arr.reduce((p,c) => (c in p ? Object.defineProperty(p, c, {enumerable : false,
writable : true,
configurable : true})
: p[c] = c,
p), {}));
console.log(uniques);
A solution for unsorted arrays with a hash table for the items. Complexity O(2n)
var array = [1, 1, 2, 2, 3, 4, 4, 5, 1],
hash = Object.create(null),
single;
array.forEach(function (a, i) {
hash[a] = a in hash ? -1 : i;
});
single = array.filter(function (a, i) {
return hash[a] === i;
});
console.log(single);
If the array is sorted, you can solve this in O(n) (see "pushUniqueSinglePass" below):
function pushUniqueSinglePass(array, unique) {
var prev; // last element seen
var run = 0; // number of times it has been seen
for (var i = 0; i < array.length; i++) {
if (array[i] != prev) {
if (run == 1) {
unique.push(prev); // "prev" appears only once
}
prev = array[i];
run = 1;
} else {
run++;
}
}
}
function pushUniqueWithSet(array, unique) {
var set = new Set();
for (var i = 0; i < array.length; i++) {
set.add(array[i]);
}
for (let e of set) {
unique.push(set);
}
}
// Utility and test functions
function randomSortedArray(n, max) {
var array = [];
for (var i = 0; i < n; i++) {
array.push(Math.floor(max * Math.random()));
}
return array.sort();
}
function runtest(i) {
var array = randomSortedArray(i, i / 2);
var r1 = [],
r2 = [];
console.log("Size: " + i);
console.log("Single-pass: " + time(
pushUniqueSinglePass, array, r1));
console.log("With set: " + time(
pushUniqueWithSet, array, r2));
// missing - assert r1 == r2
}
[10, 100, 1000, 10000,
100000, 1000000
].forEach(runtest);
function time(fun, array, unique) {
var start = new Date().getTime();
fun(array, unique);
return new Date().getTime() - start;
}
This is much more efficient than using maps or sorting (time it!). In my machine, a 1M sorted array can have its unique elements found in 18 ms; while the version that uses a set requires 10x more.

Returning a missing element from a string of integers

I'm trying to write a function that accepts an array of unique integers between 0 and 9 (inclusive), and returns the missing element. Here's what I've got. So near but so far.
var currentPlace = 0;
function getMissingElement(superImportantArray){
while (currentPlace < 9){
for (var i = 0; i < 10; i++) {
var arrayNum = superImportantArray[currentPlace]
if (i == arrayNum) {
currentPlace ++;
console.log("so it's not " + i);
}
else if (i !=arrayNum) {
console.log("try..." + i);
}
}
}
}
// run
var myArray = [0,5,1,3,2,9,7,6,4]; // this test should return 8
getMissingElement(myArray);
I'm not sure i'm approaching this correctly. Thanks for your time.
Just wanted to post my answer from the comments. A simpler way to handle this, in my opinion, is to loop over the original array, and flag a new array at the index that they represent. For example, if the number is 4, flag the 4th index in the new array. The reason for all this is because once this is done, one index should be left unflagged. All that would be left to do is find the unflagged index.
Here's an example (I commented the code here, not the fiddle):
function findMissing(array, min, max) {
var missing, unfilledArray, i, j;
// Array to hold the flags
unfilledArray = [];
for (i = min, j = max; i <= j; i++) {
// Flag the index in the new array with the current value
unfilledArray[array[i]] = true;
}
for (i = min, j = max; i <= j; i++) {
// Loop over new array and find the unflagged index
currentUnfilled = unfilledArray[i];
if (!currentUnfilled) {
// Current index not flagged
missing = i;
break;
}
}
return missing;
}
DEMO: http://jsfiddle.net/6GAyw/
The other little feature I added was that you explicitly specify the minimum and maximum value, which, in your case, is 0 and 9. This feature allows this solution to be used on any range of numbers (unlike my original comment/suggestion).
And not that I fully understand big O notation, but I believe this is O(2n), not O(n^2), since there aren't nested loops/indexOf.
If you were looking to get all missing numbers in a range, you can easily modify the function to return an array of unflagged indexes instead. Here's an example:
function findMissing(array, min, max) {
var missing, unfilledArray, i, j;
// Array to hold the missing numbers
missing = [];
// Array to hold the flags
unfilledArray = [];
for (i = min, j = max; i <= j; i++) {
// Flag the index in the new array with the current value
unfilledArray[array[i]] = true;
}
for (i = min, j = max; i <= j; i++) {
// Loop over new array and find the unflagged index
currentUnfilled = unfilledArray[i];
if (!currentUnfilled) {
// Current index not flagged
missing.push(i);
}
}
return missing;
}
DEMO: http://jsfiddle.net/zFS89/
function getMissingElement(superImportantArray){
var result = [], length = Math.max(10, superImportantArray.length);
for (var i = 0; i < length; i++) {
if(superImportantArray.indexOf(i) == -1){
result.push(i);
}
}
return result;
}
Try this. This will return an array of missing elements else return an empty array.
DEMO FIDDLE
So here is one way to do it: Since you know that the array only contains values from 0 to 9, you can build a "set" of numbers and remove each "seen" value in the array from the set:
function getMissingElement(superImportantArray){
var numbers = {};
for (var i = 0; i < 10; i++) {
numbers[i] = true
}
for (var i = 0, l = superImportantArray.length; i < l; i++) {
delete numbers[superImportantArray[i]];
}
return Object.keys(numbers);
}
This would return an array of all numbers that are missing. If there can always only be one missing number you can easily modify this to directly return the number instead.
This should do it.
function getMissingElement(arrayTest) {
// create an array with all digits
var digitsArray = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
var index;
for (var i=0; i<arrayTest.length; i++) {
// get the index of current digit on our array
index = digitsArray.indexOf(arrayTest[i]);
// if found, remove it from our array.
if (index >= 0) {
digitsArray.splice(index,1);
}
}
// the last remaining digit in the original array should be the one missing.
return (digitsArray[0]);
}
This one is better for the eyes.
function getMissingElement(superImportantArray) {
return superImportantArray.reduce(function (sum, value) {return sum - value;}, 45);
}

Count how many strings in an array have duplicates in the same array [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Array value count javascript
I have an array which contains several duplicates, what I'm trying to achieve is to count how many duplicates each unique string has in this one array.
The array looks something like this
array = ['aa','bb','cc','aa','ss','aa','bb'];
Thus I would like to do something like this
if (xWordOccurrences >= 5) {
// do something
}
But I'm not sure how I would code this.
I was thinking, create an object with each unique string, then loop through the original array, match each string with it's object and increment it's number by 1, then loop over the object to see which words had the most duplicates...
But this seems like an over complexe way to do it.
You can use an object which has keys of the Array's values and do something like this
// count everything
function getCounts(arr) {
var i = arr.length, // var to loop over
obj = {}; // obj to store results
while (i) obj[arr[--i]] = (obj[arr[i]] || 0) + 1; // count occurrences
return obj;
}
// get specific from everything
function getCount(word, arr) {
return getCounts(arr)[word] || 0;
}
getCount('aa', ['aa','bb','cc','aa','ss','aa','bb']);
// 3
If you only ever want to get one, then it'd be more a bit more efficient to use a modified version of getCounts which looks similar to getCount, I'll call it getCount2
function getCount2(word, arr) {
var i = arr.length, // var to loop over
j = 0; // number of hits
while (i) if (arr[--i] === word) ++j; // count occurance
return j;
}
getCount2('aa', ['aa','bb','cc','aa','ss','aa','bb']);
// 3
Try this function:
var countOccurrences = function(arr,value){
var len = arr.length;
var occur = 0;
for(var i=0;i<len;i++){
if(arr[i]===value){
occur++;
}
}
return occur;
}
var count = countOccurrences(['aaa','bbb','ccc','bbb','ddd'],'bbb'); //2
If you want, you can also add this function to the Array prototype:
Array.prototype.countOccurrences = function(value){
var len = this.length;
var occur = 0;
for(var i=0;i<len;i++){
if(this[i]===value){
occur++;
}
}
return occur;
}
How about you build an object with named property?
var array = ['aa','bb','cc','aa','ss','aa','bb'];
var summary = {};
var item = '';
for ( i in array){
item = array[i];
if(summary[item]){
summary[item] += 1;
}
else{
summary[item] = 1;
}
}
console.log( summary );
summary will contain like this
{aa: 3, bb: 2, cc: 1, ss: 1}
which you could then iterate on and then sort them later on if needed.
finally to get your count, you could use this summary['aa']
<script type="text/javascript">
var array = ['aa','bb','cc','aa','ss','aa','bb'];
var myMap = {};
for(i = 0; i < array.length; i++) {
var count = myMap[array[i]];
if(count != null) {
count++;
} else {
count = 1;
}
myMap[array[i]] = count;
}
// at this point in the script, the map now contains each unique array item and a count of its entries
</script>
Hope this solves your problem
var array = ['aa','bb','cc','aa','ss','aa','bb'];
var dups = {};
for (var i = 0, l = array.length; i < l; i++ ) {
dups[array[i]] = [];
}
for (str in dups) {
for (var i = 0, l = array.length; i < l; i++ ) {
if (str === array[i]) {
dups[str].push(str);
}
}
}
for (str in dups) {
console.log(str + ' has ' + (dups[str].length - 1) + ' duplicate(s)');
}
This function may do everything you need.
function countDupStr(arr, specifier) {
var count = {}, total = 0;
arr.forEach(function (v) {
count[v] = (count[v] || 0) + 1;
});
if(typeof specifier !== 'undefined') {
return count[specifier] - 1;
}
Object.keys(count).forEach(function (k) {
total += count[k] - 1;
});
return total;
}
Each value in the array is assigned and incremented to the count object. Whether or not a specifier was passed, the function will return duplicates of that specific string or the total number of duplicates. Note that this particular technique will only work on string-coercible values inside your arrays, as Javascript can only index objects by string.
What this means is that during object assignment, the keys will normalize down to strings and cannot be relied upon for uniqueness. That is to say, this function wouldn't be able to discern the difference between duplicates of 3 and '3'. To give an example, if I were to perform:
var o = {}, t = {};
o[t] = 1;
console.log(o);
The key used in place of t would eventually be t.toString(), thus resulting in the perhaps surprising object of {'[object Object]': 1}. Just something to keep in mind when working with Javascript properties.
I saw this post about it, perhaps it can help:
http://ryanbosinger.com/blog/2011/javascript-count-duplicates-in-an-array/

Alternate method to splice function in JavaScript

Hi i am working on LIME programming which is a subset of javascript.
i need to use javascript.splice to remove certain elements from my array, sad to say, LIME does not support splice function.
Any idea how do i create my own function to remove elements from an array?
Thanks for your time.
EDIT: Manage to create a simple function.
function removeElements(array, index)
{
var tempArray = new Array();
var counter = 0;
for(var i = 0; i < array.length; i++)
{
if(i != index)
{
tempArray[counter] = array[i];
counter++;
}
}
return tempArray;
}
Array.prototype.splice is fully defined in ECMA-262 §15.4.4.12, so use that as your spec and write one. e.g.
15.4.4.12 Array.prototype.splice (start, deleteCount [ , item1 [ ,item2 [ , … ] ] ] )
When the splice
method is called with two or more
arguments start, deleteCount and
(optionally) item1, item2, etc., the
deleteCount elements of the array
starting at array index start are
replaced by the arguments item1,
item2, etc. An Array object containing
the deleted elements (if any) is
returned. The following steps are
taken:...
You will probably have to create a new array, copy the members up to start from the old array, insert the new members, then copy from start + deleteCount to the end to the new array.
Edit
Here is an amended splice, the first I posted was incorrect. This one splices the array passed in and returns the removed members. It looks a bit long but I tried to keep it close to the spec and not assume support for any complex Array methods or even Math.max/min. It can be simplified quite a bit if they are.
If push isn't supported, it can be replaced fairly simply too.
function arraySplice(array, start, deleteCount) {
var result = [];
var removed = [];
var argsLen = arguments.length;
var arrLen = array.length;
var i, k;
// Follow spec more or less
start = parseInt(start, 10);
deleteCount = parseInt(deleteCount, 10);
// Deal with negative start per spec
// Don't assume support for Math.min/max
if (start < 0) {
start = arrLen + start;
start = (start > 0)? start : 0;
} else {
start = (start < arrLen)? start : arrLen;
}
// Deal with deleteCount per spec
if (deleteCount < 0) deleteCount = 0;
if (deleteCount > (arrLen - start)) {
deleteCount = arrLen - start;
}
// Copy members up to start
for (i = 0; i < start; i++) {
result[i] = array[i];
}
// Add new elements supplied as args
for (i = 3; i < argsLen; i++) {
result.push(arguments[i]);
}
// Copy removed items to removed array
for (i = start; i < start + deleteCount; i++) {
removed.push(array[i]);
}
// Add those after start + deleteCount
for (i = start + (deleteCount || 0); i < arrLen; i++) {
result.push(array[i]);
}
// Update original array
array.length = 0;
i = result.length;
while (i--) {
array[i] = result[i];
}
// Return array of removed elements
return removed;
}
If you don't care about order of the array and you're just looking for a function to perform splice, here's an example.
/**
* Time Complexity: O(count) aka: O(1)
*/
function mySplice(array, start, count) {
if (typeof count == 'undefined') count = 1
while (count--) {
var index2remove = start + count
array[index2remove] = array.pop()
}
return array
}
If you want to return the removed elements like the normal splice method does this will work:
/**
* Time Complexity: O(count) aka: O(1)
*/
function mySplice(array, index, count) {
if (typeof count == 'undefined') count = 1
var removed = []
while (count--) {
var index2remove = index + count
removed.push(array[index2remove])
array[index2remove] = array.pop()
}
// for (var i = index; i < index + count; i++) {
// removed.push(array[i])
// array[i] = array.pop()
// }
return removed
}
This modifies the original Array, and returns the items that were removed, just like the original.
Array.prototype.newSplice = function( start, toRemove, insert ) {
var remove = this.slice( start, start + toRemove );
var temp = this.slice(0,start).concat( insert, this.slice( start + toRemove ) );
this.length = 0;
this.push.apply( this, temp );
return remove;
};
Comparison test: http://jsfiddle.net/wxGDd/
var arr = [0,1,2,3,4,5,6,7,8];
var arr2 = [0,1,2,3,4,5,6,7,8];
console.log( arr.splice( 3, 2, 6 ) ); // [3, 4]
console.log( arr ); // [0, 1, 2, 6, 5, 6, 7, 8]
console.log( arr2.newSplice( 3, 2, 6 ) ); // [3, 4]
console.log( arr2 ); // [0, 1, 2, 6, 5, 6, 7, 8]
It could use a little extra detail work, but for the most part it takes care of it.
Here is a simple implement in case the Array.prototype.splice dispears
if (typeof Array.prototype.splice === 'undefined') {
Array.prototype.splice = function (index, howmany, elemes) {
howmany = typeof howmany === 'undefined' || this.length;
var elems = Array.prototype.slice.call(arguments, 2), newArr = this.slice(0, index), last = this.slice(index + howmany);
newArr = newArr.concat.apply(newArr, elems);
newArr = newArr.concat.apply(newArr, last);
return newArr;
}
}
Are there any other methods that are missing in LIME's Array implementation?
Assuming at least the most basic push() and indexOf() is available, there's several ways you could do it. How this is done would depend on whether this is destructive method or whether it should return a new array. Assuming the same input as the standard splice(index, howMany, element1, elementN) method:
Create a new array named new
push() indexes 0 to index onto the new array
Now stop at index and push() any new elements passed in. If LIME supports the standard arguments variable then you can loop through arguments with index > 2. Otherwise you'll need to pass in an array instead of a variable number of parameters.
After inserting the new objects, continue looping through the input array's elements, starting at index + howMany and going until input.length
I believe that should get you the results you're looking for.
I have used this below function as an alternative for splice()
array = mySplice(array,index,count);
above is the function call,
And this is my function mySplice()
function mySplice(array, index, count)
{
var newArray = [];
if( count > 0 )
{ count--;}
else
{ count++;}
for(i = 0; i <array.length; i++)
{
if(!((i <= index + count && i >= index) || (i <= index && i >= index + count)))
{
newArray.push(array[i])
}
}
return newArray;
}
I have done it very similar way using only one for loop
function removeElements(a,index,n){
// a=> Array , index=> index value from array to delete
// n=> number of elements you want to delete
let temp = []; // for storing deleted elements
let main_array = []; // for remaining elements which are not deleted
let k = 0;
for(let i=0;i<a.length;i++){
if((i===index) || ((index<i && i<n+index))){
temp[i]=a[i+1];
delete a[i];
}
if(a[i]!==undefined){
main_array[k] = a[i];
a[i] = main_array[k];
k++;
}
}
a=main_array;
return a;
}
a=[1,2,3,4,5];
console.log(removeElements(a,0,1));
follow link Jsfiddle
var a = [3, 2, 5, 6, 7];
var fromindex = 1
var toindex = 2;
for (var i = 0; i < a.length; i++) {
if (i >= fromindex + toindex || i < fromindex) {
console.log(a[i])
}
}
var a = [3, 2, 5, 6, 7];
var temp=[];
function splice(fromindex,toindex)
{
for (var i = 0; i < a.length; i++) {
if(i>=fromindex+toindex || i<fromindex)
{
temp.push(a[i])
}
}
return temp
}
console.log(splice(3,2))

Categories