How to check if two numbers are equal in javascript [duplicate] - javascript

This question already has answers here:
Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array
(97 answers)
Closed 3 years ago.
Let's say we have an array:
let arr = [10,10,5,11,5]
How could I check for all the numbers that are equal? ( basically duplicates )
What i thought of is a forEach and compare every number but that's not very optimal. A filter ? Maybe. Anyone has any good ideea that would be optimal?

You can use reduce to build down the values you need
let arr = [10, 10, 5, 11, 5];
let duplicates = getDuplicates(arr);
console.log(duplicates);
function getDuplicates(arr) {
let duplicates = arr.reduce((acc, item) => {
if(acc[item] !== undefined) {
acc[item] = true;
} else {
acc[item] = false;
}
return acc;
}, {});
return Object.keys(duplicates).filter(item => duplicates[item]);
}

You can use filter
let arr = [10,10,5,11,5];
const duplicates = array => array.filter((item, index) => array.some((i, idx) => i === item && idx < index));
console.log(duplicates(arr));
or reduce
let arr = [10,10,5,11,5];
const duplicates = array => array.reduce((results, item, index) => {
if (!results.some(i => i === item) && array.some((i, idx) => i === item && index !== idx)) {
results.push(item);
}
return results;
}, []);
console.log(duplicates(arr));

You can use a Set to remove the duplicates and then compare the lengths of the two arrays.
let arr1 = [10,10,5,11,5]
let arr2 = [10,11,5]
function hasDuplicates(arr) {
return arr.length != [...new Set(arr)].length
}
console.log(hasDuplicates(arr1))
console.log(hasDuplicates(arr2))

Really quick with every
let arr = [10,10,5,11,5]
//arr = [10,10,10,10]
if (arr.every( v => v === arr[0] )) {
console.log("yes")
} else {
console.log("no")
}
Or using Lodash
let arr = [10,10,5,11,5]
//arr = [10,10,10,10]
if (_.uniq(arr).length == 1) {
console.log("yes")
} else {
console.log("no")
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

Related

Unable to push elements in a new array in javascript

I am writing a very easy function where I am checking the even numbers from an array of integer and adding those even numbers into the new array.
But after getting the even numbers from first array when I am trying to push into second array its showing undefined.
const arr = [1,2,3,4,5,6];
const newArr = [];
const loop = () => {
for (var item of array) {
if (item % 2 == 0) {
console.log(item);
newArr.push(item);
}
}
};
console.log(loop());
Output
2
4
6
undefined
Why new array is showing undefined.
You can do it simply with forEach.
const arr = [1,2,3,4,5,6];
const newArr = [];
arr.forEach(item => {
if (item % 2 == 0) {
newArr.push(item);
}
})
console.log(newArr);
either return the newArray or execute the loop method and print the new Array.
The reason why you get undefined is because loop is currently a void operator and returning nothing. so if you want the loop method to return the array then the second code sample I showed is the better solution. if you just want to print the array then the first one does the trick.
const arr = [1,2,3,4,5,6];
const newArr = [];
arr.forEach(item => {
if (item % 2 == 0) {
newArr.push(item);
}
})
console.log(newArr);
or
const arr = [1,2,3,4,5,6];
const loop = () => {
const newArr = [];
for (var item of arr) {
if (item % 2 == 0) {
console.log(item);
newArr.push(item);
}
}
return newArr
};
console.log(loop());
both will work.

Javascript: Remove element from array

I have an array and I want to delete some elements. My array is arrayAuxiliar. My code is the following one:
for( var i = 0; i < arrayAuxiliar.length; i++)
{
if (arrayAuxiliar[i] == valueFirts) {
arrayAuxiliar.splice(i,1);
}
else if(arrayAuxiliar[i] == value){
arrayAuxiliar.splice(i,1);
}
}
Example of what is happening:
Initial values: arrayAuxiliar = [3,2,1], valueFirst = 1, value = 2
Final values: arrayAuxiliar = [3,1]
I know this happens because splice() changes the original array and that's for this reason the comparasion between arrayAuxiliar[i] == valueFirts is never true. I've also tried to use remove arrayAuxiliar[i] but it returns [3,,].
How can I solve this situation in order to get the only element that does not verify the conditions which is 3? The idea was the final result be [3] and I could get it by a arrayAuxiliar[0] command.
Use filter and includes method
const array = [3, 2, 1]
const remove_list = [2, 1]
const res = array.filter(num => !remove_list.includes(num))
console.log(res)
I think using filter would be more appropiate. You can try:
let arrayAuxiliar = [3, 2, 1]
const valueFirst = 1
const value = 2
arrayAuxiliar = arrayAuxiliar.filter(i => i !== valueFirst && i !== value)
console.log(arrayAuxiliar)
I would use Array.prototype.filter():
const arr = [3,2,1];
const valueFirst = 1;
const value = 2;
console.log(arr.filter(item => ![value, valueFirst].includes(item)));
Also you can use reduce function
function test(arrayAuxiliar, valueFirts, value) {
return arrayAuxiliar.reduce((acc,rec) => {
if ((rec === value) || (rec === valueFirts)) {
return [...acc]
}
return [...acc, rec]
}, [])
}
console.log(test([3,2,1,4,1,2,2,3,1,4,5,8,2,5], 1, 2))

filtering 2 arrays for unique elements

I write a function that receives 2 arrays and returns an array that has elements that exist in both arrays.
For example, if I pass [6,7,8,9] and [1,8,2,6], it should return [6,8].
My aim is not to use loops here.
I use this code:
const uniqueElements= (arr1, arr2) => {
return arr1.filter(it1=> arr2.filter((it2) => it2===it1).length>0)
}
However, if there are duplicate elements in arrays (e.g. [6,7,8,9,6] and [1,8,2,6,6]), it returns [6, 8, 6].
How should I mend my code so that it would return only unique elements without duplicates? Is it possible without using loops?
If you just want to get unique value which appears on both of the array, you just first change both of the array's to Set, loop through one Set and check if it's present on other or not, if it present return true from filter else return false,
const uniqueElements= (arr1, arr2) => {
let set1 = new Set(arr1)
let set2 = new Set(arr2)
return [...set1].filter(it1=> set2.has(it1))
}
console.log(uniqueElements([6,7,8,9],[1,8,2,6]))
console.log(uniqueElements([6,7,8,9,6],[1,8,2,6,6]))
Ref to read about Set
Set MDN
For your scenario use this -
constant uniqueElements= (arr1, arr2) => {
return Array.from(new Set(arr1.filter(it1=> arr2.filter((it2) => it2===it1).length>0)))
}
Hope this helps
Solution using Set from https://2ality.com/2015/01/es6-set-operations.html:
const uniqueElements = (arr1, arr2) => {
const a = new Set(arr1);
const b = new Set(arr2);
const intersection = new Set(
[...a].filter(x => b.has(x)));
return Array.from(intersection);
}
Simply you can just use Array#some() method to write the condition inside your Array#filter() method's callback:
const uniqueElements = (arr1, arr2) => {
let viewed = [];
return arr1.filter(it1 => {
let found = arr2.some((it2) => it2 === it1) && viewed.indexOf(it1) == -1;
viewed.push(it1);
return found;
});
}
Note:
This doesn't take duplicates, with the use of viewed array and viewed.indexOf(it1) == -1 condition.
Demo:
const uniqueElements = (arr1, arr2) => {
let viewed = [];
return arr1.filter(it1 => {
let found = arr2.some((it2) => it2 === it1) && viewed.indexOf(it1) == -1;
viewed.push(it1);
return found;
});
}
let a1 = [6,7,8,9,6];
let a2 = [1,8,2,6,6];
console.log(uniqueElements(a1, a2));

Count the repetition of an element in an array using a function with one parameter

Good Day, I am trying to count how many times a particular element in an array appears. I tried but my code below counts only one of the array even if it appears more than once (this is not the problem). I want it to return the amount of time each element appears. For example
let arr = [1, 3, 2, 1];
this should return
{1:2} {3:1} {2:1}
My code returns 3 (as in it just doesn't count one twice)
How do i go about this?
Below is my code
function numberCount(number) {
let count = 0;
number.forEach(function (item, index) {
if (number.indexOf(item) == index) count++;
});
console.log(count);
}
While iterating over number (better to call it arr, it's an array, not a number), use an object to keep track of the number of times each number has occured so far. Then, iterate over the resulting object's entries to create the objects desired:
let arr = [1, 3, 2, 1];
function numberCount(arr) {
let count = 0;
const obj = arr.reduce((a, num) => {
a[num] = (a[num] || 0) + 1;
return a;
}, {});
return Object.entries(obj).map(([key, val]) => ({ [key]: val }));
}
console.log(numberCount(arr));
Numeric keys always come in numeric order in an object. If you want the objects in the output to come in insertion order (eg, the object with key 3 before the object with key 2), then use a Map instead of an object (map keys will be iterated over in insertion order):
let arr = [1, 3, 2, 1];
function numberCount(arr) {
let count = 0;
const map = arr.reduce((a, num) => (
a.set(num, (a.get(num) || 0) + 1)
), new Map());
return [...map.entries()]
.map(([key, val]) => ({ [key]: val }));
}
console.log(numberCount(arr));
You should filter out these numbers, then use the length:
let arr = [1, 3, 2, 1];
function itemCount(array) {
var sorted = array.sort()
var uniqueCount = sorted.filter((v, i, a) => a.indexOf(v) == i);
var count = [];
uniqueCount.forEach(item => {
var itemCount = sorted.filter(e => e == item).length;
count.push({[item]: itemCount});
});
return count;
}
console.log(itemCount(arr));
I would suggest not reinventing the wheel, and instead use lodash which already has this function. Using countBy() you will get an object you can then convert into your desired result. For example:
const arr = [1, 3, 2, 1]
const count = _.countBy(arr)
const result = Object.keys(count).map(k => ({ [k]: count[k] }))
console.log(result)
<script src="https://cdn.jsdelivr.net/npm/lodash#4.17.11/lodash.min.js"></script>

Find the first unique value in an array or string

How can I get one unique value in an array or string? Only the first value. Pure JS only.
My example:
function searchValue () {
let inputText = [1,1,4,2,2,2,3,1];
let foundedValue;
for (let i = 0; i < inputText.length; i++) {
if (i === inputText.indexOf(inputText[i]) && i === inputText.lastIndexOf(inputText[i])) {
foundedValue = inputText[i];
break;
} else {
foundedValue = "not founded.";
}
}
return foundedValue;
}
console.log("Search value: "+ searchValue())
Answer is 4.
But, I need a short solution. Using the find() and filter() functions.
You can find the first unique item in your array using find() and comparing indexOf() to lastIndexOf() to determine whether or not there is more than one instance of an item in the array. If you need to find unique characters in a string, then you can first split it into an array and then use the same approach.
const arr = [1, 1, 4, 2, 2, 2, 3, 1];
const result = arr.find((x) => arr.indexOf(x) === arr.lastIndexOf(x));
console.log(result);
// 4
const text = 'aadbbbca';
const textarr = text.split('');
const textresult = textarr.find((x) => textarr.indexOf(x) === textarr.lastIndexOf(x));
console.log(textresult);
// d
You can try this.
const arr = [1, 1, 4, 2, 2, 2, 3, 1];
let r = {};
arr.map(a => r[a] = (r[a] || 0) +1)
var res = arr.find(a => r[a] === 1 )
console.log(res)
You can use js Set() object.
At first you could create a Set of duplicated elements.
const inputText = [1,1,4,2,2,2,3,1];
const duplicatesSet= inputText.reduce((dupSet, el) =>
inputText.filter(arrEl => arrEl === el).length > 1 ?
dupSet.add(el) : dupSet
, new Set());
Second you could use array.find. It returns first duplicated element.
const firstDupElement = inputText.find(el => duplicatesSet.has(el));
const searchValue = (_param) => {
for (let i= 0; i < _param.length; i+= 1) {
if (_param.indexOf(_param[i]) === _param.lastIndexOf(_param[i])) return _param[i];
}
return "not founded.";
}
let arr = [1,1,2,2,2,1,3,1,4,4,5]
const dupelearray = (array) => {
let arr2 =[...arr]
let ele = []
let state = false
arr2.map((i,index)=>{
arr2.splice(index,1)
arr.map((j)=>{
return arr2.includes(j) ? null : state=true
})
state && ele.push(i)
state=false
arr2.splice(index,0,i)
})
return console.log(arr.indexOf(ele[0]))
}
dupelearray(arr)
wow i didnt knew lastindexof method and was making this algo so difficult
btw this solution also works but definitely i am new in algo so this will take much more time but the solution still works!!!!!! damn should remember more methods or you have to think so much -_-

Categories