i want to check the array for the same datatypes. i found other solutions here but i want to do it with for loop and if conditonals.
Can someone please explain, why my code is not working:
thank you very much!
function sameDataType(array){
const helper = []
for(let i = 0; i < array.length; i++){
let dataType0 = typeof(array[i])
let dataType1 = typeof(array[i+1])
if(dataType0 === dataType1){
helper.push(1)
} else {
helper.push("not")
}
}
for(let j = 0; j < helper.length; j++){
if(helper[j] === helper[j+1]){
return "same"
} else {
return "different"
}
}
}
console.log(sameDataType([1, 1, "string"]))
Please use Array.map and Array.filter function.
First you get array of types.
And then filter it with removing the duplicated values.
Then check the length.
Like this.
function sameDataType1(array){
return array.map(val => typeof val).filter((val, index, self) => self.indexOf(val) === index).length === 1 ? "same" : "different";
}
console.log(sameDataType1([1, 1, "string"]))
Will try to improve upon your code only.
Firstly check if the array even has enough elements. If only one element, simply return same.
Then make sure you run your loop till the correct indices. Notice you have i+1 & j+1 in your code. You do arr[arr.length+1], you are getting undefined.
Also check for the condition when you have only two elements.
function sameDataType(array){
if(array.length > 1 ) {
const helper = []
for(let i = 0; i < array.length - 1; i++){
let dataType0 = typeof(array[i])
let dataType1 = typeof(array[i+1])
if(dataType0 === dataType1){
helper.push(1)
} else {
helper.push("not")
}
}
if(helper.length === 1 ){
if(helper[0] === 1) return "same";
return "different";
}
for(let j = 0; j < helper.length-1; j++){
if(helper[j] === 1 && helper[j] === helper[j+1]){
return "same"
} else {
return "different"
}
}
}
return "same";
}
console.log(sameDataType([1, 1 , "string"]))
console.log(sameDataType([1, "string:" ]))
console.log(sameDataType(["string", "string" , "string"]))
Sum all numbers in an array containing nested arrays
arraySum([1,[2,3],[[4]],5]); // 15
I have written this so far ..
var newArray = array.slice();
newArray = newArray.flat(Infinity);
var sum = 0;
if (newArray.length === 1) {
return array[0];
}
if (newArray.length === 0) {
return 0;
}
for (var i = 0; i < newArray.length; i++) {
if (typeof newArray[i] === "number") {
sum += newArray[i];
}
}
return arraySum(newArray);
};
If I put return sum it works perfect, but the exercise is calling for recursion.
If you want to use recursion, then replace the for loop with returning the value of the first element of the array, plus the sum of the rest of the elements in the array:
const arraySum = (array) => {
var newArray = array.slice();
newArray = newArray.flat(Infinity);
var sum = 0;
if (newArray.length === 1) {
return array[0];
}
if (newArray.length === 0) {
return 0;
}
return array[0] + arraySum(newArray.slice(1));
};
console.log(arraySum([1,[2,3],[[4]],5]));
But the .flat seems weird to be doing on every iteration. Consider doing it only once, in a second default argument that gets passed along:
const arraySum = (arr, arrFlat = arr.flat(Infinity)) => {
return arrFlat.length
? arrFlat[0] + arraySum(arr, arrFlat.slice(1))
: 0;
};
console.log(arraySum([1,[2,3],[[4]],5]));
Or check to see if the current element being iterated over is an array instead of using .flat, to see whether you need to iterate over the subarray with another recursive call to arraySum or just add the number:
const arraySum = (arr) => {
if (!arr.length) return 0;
const rest = arraySum(arr.slice(1));
return typeof arr[0] === 'number'
? arr[0] + rest
: arraySum(arr[0]) + rest;
};
console.log(arraySum([1,[2,3],[[4]],5]));
I am trying to solve a problem I'm facing in Javascript, I am totally new to JS. This is my code:
function filterOutStringfromArr(array) {
var arr = []
for (var i = 0; i < array.length; i++) {
if (typeof array[i] === 'number') {
arr[i] = array[i]
}
}
console.log(arr)
}
filterOutStringfromArr([1,2,'A','B',123])
when I run this, I get this result: [ 1, 2, <2 empty items>, 123 ].
I know this is happening because the length of my array is 5. But I want to append just the filtered value to the empty array arr[]. How can I do this?
function filterOutStringfromArr(array) {
var arr = []
for (var i = 0; i < array.length; i++) {
if (typeof array[i] === 'number') {
arr.push(array[i])
}
}
console.log(arr)
}
filterOutStringfromArr([1,2,'A','B',123])
MDN link that is pretty good
You should use push that will append to the end of an array. By inserting the found element into spot i you are going from index 3 to 5 thus the empty elements.
I suggest to use the Array.prototype.push() method.
function filterOutStringsfromArray(array) {
var arr = [];
for (let i = 0; i < array.length; i++) {
if (typeof array[i] === 'string') {
arr.push(array[i]);
}
}
return arr;
}
filterOutStringfromArr([5, 2, 'h', 2, 's', 2]) // Expected Output: ['h', 's']
Filter method will solve your issue.
function filterOutStringfromArr(array) {
const newArray = array.filter(item => {
if (typeof item === 'number') {
return item;
}
})
console.log(newArray);
}
filterOutStringfromArr([1,2,'A','B',123])
Personally i would just use a normal array filter function and test the condition. let native array.filter function do the work for you. The below will filter the array and return a new array (not modify the existing array).
function filterToArrayOfNumbers(arrayElement) {
return typeof arrayElement === 'number';
}
console.log([1,2,'A','B',123].filter(filterToArrayOfNumbers));
arr[i] = array[i] // <------------ your issue
i is still being incremented, so when you are looking at your last number 123, (index 4), it will set the new array at index 4 (leaving 2 and 3 empty)
rather than setting it explicitly, you can do arr.push(array[i])
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push
just a quick question. How can I retrieve elements in an array given that the elements cannot be divided by other elements in an array? for example= arr =[2,3,4,5,6,7,8,9,10,11,12,13,14,15,16] and collection =[2,3,5,7], then the result would be result =[11,13]
I have tried with this code , but it didn't work
for(var i=0; i<arr.length;i++){
for (var j=0; j<collection.length; j++){
if (arr[i]/collection[j] === 0){
arr.splice(i,1);
}
}
}
Something like this
1) using filter and forEach:
var arr =[2,3,4,5,6,7,8,9,10,11,12,13,14,15,16];
var collection =[2,3,5,7];
function notDivided(arr1, arr2) {
return arr1.filter( function(item) {
var can_be_divided = false;
arr2.forEach( function(item_to_divide) {
if (item % item_to_divide === 0) can_be_divided = true;
});
return !can_be_divided;
});
}
var new_array = notDivided(arr,collection);
console.log(new_array);
2) using filter and some (#torazaburo's suggestion)
function notDivided(arr1, arr2) {
return arr1.filter( function(item) {
return !arr2.some( function(item_to_divide) {
return (item % item_to_divide === 0);
});
});
}
Or, yet, using arrow functions:
notDivided = (arr1, arr2) => arr1.filter( (item) => !arr2.some( (item_to_divide) => item % item_to_divide === 0 ) );
declare new array to collect results
use % symbol to check
example 4 % 2 = 0
this mean 4 can be divided by 2 because result is 0 so you can make
if (!(arr[i]%collection[j] === 0)){
newarr.push(arr[i])
}
edited
if you wanna example without think here return what you post too
var arr =[2,3,4,5,6,7,8,9,10,11,12,13,14,15,16];
var collection =[2,3,5,7];
var newarr=[];
var addtonew = 0;
for(var i=0; i < arr.length; i++){
addtonew = -1;
for (var j=0; j<collection.length; j++){
if (arr[i]%collection[j] === 0)
{
addtonew = -1;
break;
}
addtonew = arr[i];
}
if (addtonew > -1 )
newarr.push(addtonew);
}
#[11, 13]
This question already has answers here:
In Javascript, how do I check if an array has duplicate values?
(9 answers)
Closed 10 months ago.
I wanted to write a javascript function which checks if array contains duplicate values or not.
I have written the following code but its giving answer as "true" always.
Can anybody please tell me what am I missing.
function checkIfArrayIsUnique(myArray)
{
for (var i = 0; i < myArray.length; i++)
{
for (var j = 0; j < myArray.length; j++)
{
if (i != j)
{
if (myArray[i] == myArray[j])
{
return true; // means there are duplicate values
}
}
}
}
return false; // means there are no duplicate values.
}
An easy solution, if you've got ES6, uses Set:
function checkIfArrayIsUnique(myArray) {
return myArray.length === new Set(myArray).size;
}
let uniqueArray = [1, 2, 3, 4, 5];
console.log(`${uniqueArray} is unique : ${checkIfArrayIsUnique(uniqueArray)}`);
let nonUniqueArray = [1, 1, 2, 3, 4, 5];
console.log(`${nonUniqueArray} is unique : ${checkIfArrayIsUnique(nonUniqueArray)}`);
let arr = [11,22,11,22];
let hasDuplicate = arr.some((val, i) => arr.indexOf(val) !== i);
// hasDuplicate = true
True -> array has duplicates
False -> uniqe array
This should work with only one loop:
function checkIfArrayIsUnique(arr) {
var map = {}, i, size;
for (i = 0, size = arr.length; i < size; i++){
if (map[arr[i]]){
return false;
}
map[arr[i]] = true;
}
return true;
}
You got the return values the wrong way round:
As soon as you find two values that are equal, you can conclude that the array is not unique and return false.
At the very end, after you've checked all the pairs, you can return true.
If you do this a lot, and the arrays are large, you might want to investigate the possibility of sorting the array and then only comparing adjacent elements. This will have better asymptotic complexity than your current method.
Assuming you're targeting browsers that aren't IE8,
this would work as well:
function checkIfArrayIsUnique(myArray)
{
for (var i = 0; i < myArray.length; i++)
{
if (myArray.indexOf(myArray[i]) !== myArray.lastIndexOf(myArray[i])) {
return false;
}
}
return true; // this means not unique
}
Here's an O(n) solution:
function hasDupes(arr) {
/* temporary object */
var uniqOb = {};
/* create object attribute with name=value in array, this will not keep dupes*/
for (var i in arr)
uniqOb[arr[i]] = "";
/* if object's attributes match array, then no dupes! */
if (arr.length == Object.keys(uniqOb).length)
alert('NO dupes');
else
alert('HAS dupes');
}
var arr = ["1/1/2016", "1/1/2016", "2/1/2016"];
hasDupes(arr);
https://jsfiddle.net/7kkgy1j3/
Another solution:
Array.prototype.checkIfArrayIsUnique = function() {
this.sort();
for ( var i = 1; i < this.length; i++ ){
if(this[i-1] == this[i])
return false;
}
return true;
}
function hasNoDuplicates(arr) {
return arr.every(num => arr.indexOf(num) === arr.lastIndexOf(num));
}
hasNoDuplicates accepts an array and returns true if there are no duplicate values. If there are any duplicates, the function returns false.
Without a for loop, only using Map().
You can also return the duplicates.
(function(a){
let map = new Map();
a.forEach(e => {
if(map.has(e)) {
let count = map.get(e);
console.log(count)
map.set(e, count + 1);
} else {
map.set(e, 1);
}
});
let hasDup = false;
let dups = [];
map.forEach((value, key) => {
if(value > 1) {
hasDup = true;
dups.push(key);
}
});
console.log(dups);
return hasDup;
})([2,4,6,2,1,4]);
Late answer but can be helpful
function areThereDuplicates(args) {
let count = {};
for(let i = 0; i < args.length; i++){
count[args[i]] = 1 + (count[args[i]] || 0);
}
let found = Object.keys(count).filter(function(key) {
return count[key] > 1;
});
return found.length ? true : false;
}
areThereDuplicates([1,2,5]);
The code given in the question can be better written as follows
function checkIfArrayIsUnique(myArray)
{
for (var i = 0; i < myArray.length; i++)
{
for (var j = i+1; j < myArray.length; j++)
{
if (myArray[i] == myArray[j])
{
return true; // means there are duplicate values
}
}
}
return false; // means there are no duplicate values.
}
Returns the duplicate item in array and creates a new array with no duplicates:
var a = ["hello", "hi", "hi", "juice", "juice", "test"];
var b = ["ding", "dong", "hi", "juice", "juice", "test"];
var c = a.concat(b);
var dupClearArr = [];
function dupArray(arr) {
for (i = 0; i < arr.length; i++) {
if (arr.indexOf(arr[i]) != i && arr.indexOf(arr[i]) != -1) {
console.log('duplicate item ' + arr[i]);
} else {
dupClearArr.push(arr[i])
}
}
console.log('actual array \n' + arr + ' \nno duplicate items array \n' + dupClearArr)
}
dupArray(c);
const containsMatches = (a1, a2) => a1.some((v) => a2.includes(v));
If your array nests other arrays/objects, using the Set approach may not be what you want since comparing two objects compares their references. If you want to check that their contained values are equal, something else is needed. Here are a couple different approaches.
Approach 1: Map using JSON.stringify for keys
If you want to consider objects with the same contained values as equal, here's one simple way to do it using a Map object. It uses JSON.stringify to make a unique id for each element in the array.
I believe the runtime of this would be O(n * m) on arrays, assuming JSON.stringify serializes in linear time. n is the length of the outer array, m is size of the arrays. If the objects get very large, however, this may slow down since the keys will be very long. Not a very space-efficient implementation, but it is simple and works for many data types.
function checkArrayDupeFree(myArray, idFunc) {
const dupeMap = new Map();
for (const el of myArray) {
const id = idFunc(el);
if (dupeMap.has(id))
return false;
dupeMap.set(id, el);
}
return true;
}
const notUnique = [ [1, 2], [1, 3], [1, 2] ];
console.log(`${JSON.stringify(notUnique)} has no duplicates? ${checkArrayDupeFree(notUnique, JSON.stringify)}`);
const unique = [ [2, 1], [1, 3], [1, 2] ];
console.log(`${JSON.stringify(unique)} has no duplicates? ${checkArrayDupeFree(unique, JSON.stringify)}`);
Of course, you could also write your own id-generator function, though I'm not sure you can do much better than JSON.stringify.
Approach 2: Custom HashMap, Hashcode, and Equality implementations
If you have a lot of big arrays, it may be better performance-wise to implement your own hash/equality functions and use a Map as a HashMap.
In the following implementation, we hash the array. If there is a collision, map a key to an array of collided values, and check to see if any of the array values match according to the equality function.
The downside of this approach is that you may have to consider a wide range of types for which to make hashcode/equality functions, depending on what's in the array.
function checkArrayDupeFreeWHashes(myArray, hashFunc, eqFunc) {
const hashMap = new Map();
for (const el of myArray) {
const hash = hashFunc(el);
const hit = hashMap.get(hash);
if (hit == null)
hashMap.set(hash, [el]);
else if (hit.some(v => eqFunc(v, el)))
return false;
else
hit.push(el);
}
return true;
}
Here's a demo of the custom HashMap in action. I implemented a hashing function and an equality function for arrays of arrays.
function checkArrayDupeFreeWHashes(myArray, hashFunc, eqFunc) {
const hashMap = new Map();
for (const el of myArray) {
const hash = hashFunc(el);
const hit = hashMap.get(hash);
if (hit == null)
hashMap.set(hash, [el]);
else if (hit.some(v => eqFunc(v, el)))
return false;
else
hit.push(el);
}
return true;
}
function arrayHasher(arr) {
let hash = 19;
for (let i = 0; i < arr.length; i++) {
const el = arr[i];
const toHash = Array.isArray(el)
? arrayHasher(el)
: el * 23;
hash = hash * 31 + toHash;
}
return hash;
}
function arrayEq(a, b) {
if (a.length != b.length)
return false;
for (let i = 0; i < a.length; i++) {
if ((Array.isArray(a) || Array.isArray(b)) && !arrayEq(a[i], b[i]))
return false;
else if (a[i] !== b[i])
return false;
}
return true;
}
const notUnique = [ [1, 2], [1, 3], [1, 2] ];
const unique = [ [2, 1], [1, 3], [1, 2] ];
console.log(`${JSON.stringify(notUnique)} has no duplicates? ${checkArrayDupeFreeWHashes(notUnique, arrayHasher, arrayEq)}`);
console.log(`${JSON.stringify(unique)} has no duplicates? ${checkArrayDupeFreeWHashes(unique, arrayHasher, arrayEq)}`);
function checkIfArrayIsUnique(myArray)
{
isUnique=true
for (var i = 0; i < myArray.length; i++)
{
for (var j = 0; j < myArray.length; j++)
{
if (i != j)
{
if (myArray[i] == myArray[j])
{
isUnique=false
}
}
}
}
return isUnique;
}
This assume that the array is unique at the start.
If find two equals values, then change to false
i think this is the simple way
$(document).ready(function() {
var arr = [1,2,3,9,6,5,6];
console.log( "result =>"+ if_duplicate_value (arr));
});
function if_duplicate_value (arr){
for(i=0;i<arr.length-1;i++){
for(j=i+1;j<arr.length;j++){
if(arr[i]==arr[j]){
return true;
}
}
}
return false;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
var c=[2,2,3,3,5,5,4,4,8,8];
for(var i=0; i<b.length; i++){
for(var j=i+1; j<b.length; j++){
if(c[i]==c[j]){
console.log(c[j]);
}
}
}