Check if element is in array twice time [duplicate] - javascript

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');
}
}
}

Related

Trying to move elements into empty arrays. Code runs, but nothing is being returned [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I'm very new to coding and I've been trying to practice arrays and storing new elements into empty arrays. this code runs, but nothing comes back. what am I doing wrong?
const myArr = [2,2,3,4,4,5]
const evenArray = [];
const oddArray = [];
for (let i=0; i<myArr.length; i++) {
if (myArr[i] % 2 == 0)
myArr.push(evenArray[i])
return evenArray
} if (myArr[i % 2 !== 0]) {
myArr.push(oddArray[i])
}
return oddArray
console.log(evenArray)
There are a lot of problems with your code.
For example:
You are trying to use return out of a function.
You are pushing into myArr, instead of even or odd arrays..
You are also not correctly using the curly braces. Here is how you should do it.
const myArr = [2, 2, 3, 4, 4, 5];
const evenArray = [];
const oddArray = [];
for (let i = 0; i < myArr.length; i++) {
if (myArr[i] % 2 === 0) {
// even
evenArray.push(myArr[i]);
} else {
// odd
oddArray.push(myArr[i]);
}
}
console.log({ evenArray });
console.log({ oddArray });
console.log({ myArr });
.as-console-wrapper { min-height: 100%!important; top: 0; }
Main problems with how you are writing your code:
Return statement not within function
Not using if statements correctly
Here is a solution:
const myArr = [2, 2, 3, 4, 4, 5];
const evenArray = [];
const oddArray = [];
for (let i = 0; i < myArr.length; i++) {
if (myArr[i] % 2 == 0) {
evenArray.push(myArr[i]);
} else {
// We can just use an else statement here because anything thats not even is odd
oddArray.push(myArr[i]);
}
}
console.log(evenArray, oddArray); // Now that the loop has run console.log the results
Note: Stack overflow is not the place to ask questions about the basics of coding! I would recommend checking out freeCodeCamp.org and their YouTube channel because you seem to have problems with the fundamental principals of js.
You dont need return statements. Only save values into new arrays.
const myArr = [2,2,3,4,4,5]
const evenArray = [];
const oddArray = [];
for (var i=0; i < myArr.length; i++) {
if (myArr[i] % 2 == 0) {
evenArray.push(myArr[i]) //push even elements into evenArray
}
if (myArr[i] % 2 !== 0) {
oddArray.push(myArr[i]) //push odd elements into oddArray
}
}
console.log(evenArray) //evenArray will have even numbers
console.log(oddArray) //oddArray will have odd numbers
Please share which programming language you're using.
As per your code it seems you are pushing the empty array value to your myArr array. Try using evenArray.push(myArr[i]) instead of myArr.push(evenArray[i])

How to create an array with 'a' repeated 'b' times [duplicate]

This question already has answers here:
Create an array with same element repeated multiple times
(25 answers)
Closed 2 years ago.
I am trying to create a function that takes in two vairables a and b, this function will create an array with variable a reapeated b times.
This is how far I have gone but It's not outputting th correct number of items in the array:
var createArr = function(a, b) {
// returns an array with variable a repeated b times.
if (typeof b == 'number') {
var arr = [];
for (var i = 0; i <= b; i++) {
arr.push(a);
};
}
return arr;
};
createArr("ready",3)
Easy:
function createArr(a, b) {
return Array(b).fill(a);
}
If you use <= and the value “3” for “b”, the loop will run once for 0, 1, 2, and 3. Oops, that’s 4 times.
Instead you want to use < so the loop will run once for 0, 1, then 2, and not for 3.
See also https://en.wikipedia.org/wiki/Fencepost_error
for loop, break will be < not <= because when <= for loop start with 0 and break when it 3 so loop 4 times when need to loop 3 times so need an use <
var createArr = function(a, b) {
// returns an array with variable a repeated b times.
if (typeof b == 'number') {
var arr = [];
for (var i = 0; i < b; i++) {
arr.push(a);
};
}
return arr;
};
console.log(createArr("ready",3));

How to check if all values of a given array are unique [duplicate]

This question already has answers here:
Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array
(97 answers)
Closed 5 years ago.
I need to write a function in JavaScript which would return a boolean after checking if all values of a given array are unique.
Examples
[1,2,3,4] true
[1,2,1,4] false, since the array has value '1' twice
You compare length of your array and size of the Set which always contains uniq entries.
const isUnique = (arrToTest) =>
arrToTest.length === new Set(arrToTest).size
console.log(isUnique([1,1,2,3]));
console.log(isUnique([1,2,3]));
You can sort and check for each sibling.
var array1 = [1,2,3,4];
var array2 = [1,2,1,4];
function decorate(array) {
array.uniques = function() {
this.sort();
for (var i = 0; i < this.length; i++) {
if (this[i + 1] === this.length) return true;
if (this[i] === this[i + 1]) return false;
}
}
}
decorate(array1);
decorate(array2);
console.log(array1.uniques());
console.log(array2.uniques());
You can use a custom object
function checkUnique(array)
{ var i,obj={};
for(i=0;i<array.length;i++)
{ if(obj[array[i]])
return false;
obj[array[i]]=true;
}
return true;
}
console.log(checkUnique([1,2,3,4]));
console.log(checkUnique([1,2,1,4]));

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;
}

Count occurrences of array elements with JavaScript [duplicate]

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]

Categories

Resources