Checking if the array has duplicates apart from one element Javascript Dice - javascript

Hi im struggling to impliment a function to simply check if an array has all the same numbers apart from one.
I have tried a few methods now and i feel like im getting nowhere.
The reason for this is for a dice game the user can select a number of dices and then roll and score bonus points for duplicate numbers and other sequences ect..
I thought it would be simple to check if the array had all duplciates apart from one element in the array but i cant get it to work.
I was thinking of something like check the elements in the aray and see if the all the elements are the same value apart from one by using something with the array.length-1.
Examples dice values which would be true:
[1,2,2,2] or [4,4,2,4] (for 4 dice) //true
[1,1,6] (for 3 dice )//true
I tried something like this :
function countDuplicate(array){
var count=0;
var sorted_array=array.sort();
for (let i=1;i<sorted_array.length;i++)
{
if (sorted_array[i] ==sorted_array[i+1]){
count+=count;}
}
if (count===sorted_array.length-1){
return true;
}
return false;
}
but it doesnt seem to work.
Hope this is enough sorry im new to javascript and stackoverflow.

One way to implement this is to build an array of counts of each of the values in the array. This list can then be checked to ensure its length is 2 and the minimum count is 1:
const countDuplicate = (array) => {
let counts = Object.values(array.reduce((c, v) =>
(c[v] = (c[v] || 0) + 1, c), {}));
return counts.length == 2 && Math.min(...counts) == 1
}
console.log(countDuplicate([1,2,2,2]));
console.log(countDuplicate([4,4,2,4]));
console.log(countDuplicate([1,1,6]));
console.log(countDuplicate([2,2,4,4]));
console.log(countDuplicate([1,2]));

This is using Set and it compares the length of original array and array of removed duplicates:
const hasDuplicates = (arr = []) => {
const noDuplicates = [...new Set(arr)];
return arr.length !== noDuplicates.length;
};
console.log(hasDuplicates([1,2,3]));
console.log(hasDuplicates([1,2,3,1]));

if you're simply just wanting to check if all values are the same except for one in array you can just use this.
function oneMultiple(array) {
const set = new Set(array)
return set.size === 2
}

if you want to simply use one values USE THIS
function oneMultiple(array) {
const set = new Set(array)
return set.size === 2
}

Related

React.JS Storing mapped API repsonse into a new array based on matching values

Using React, I have data from an API response. I mapped the data and am storing the visitID, which would be the main identifier, into a variable. What I would like to do is look for any matching visitID values and store them into a new array, the issue I'm having is each instance is being stored in it's own array, for example:
['7065682'] at Index 0
['7065682'] at Index 1
['7065682'] at Index 2
['7047674'] at Index 3
['7047674'] at Index 4
I would like to look through each iteration and check all, put matching values into it's own array so I can write some logic based off each unique value. I just don't understand how to look through the next iteration. Here's my code, and the function 'duplicateVisitID' that I've been trying, but it doesn't give me the results I'm looking for.
{
Object.keys(this.state.EncounterData).length !== 0 ?
Object.values(this.state.EncounterData).map((encounter, i) => {
const visitID = [encounter.resource.identifier[1].value];
console.log(visitID, i);
const duplicateVisitID = function (visitID) {
if (visitID[i] === visitID[i])
return [visitID.concat(visitID[i])]
}
I am not sure what do you want to do, but if I understood right you want new array with only strings that are unique, not repeating. If yes see the code below. This is not the best performing one because of iteration inside iteration, but it will work for you. You can optimize it later by applying some algorithms.
The newArr is equal to ['7065682', '7047674']
const EncounteredData = [['7065682'], ['7065682'], ['7065682'], ['7047674'], ['7047674']];
const newArr = [];
for(let i of EncounteredData) {
for(let j of EncounteredData) {
if((i[0] !== j[0]) && !newArr.includes(i[0])) newArr.push(i[0]);
}
}
console.log(newArr);
If I understand correctly, you want an array of unique values? If so then you can use the map function and add any unique values to an array if the value is not already in it:
const uniqueVals = [];
EncounteredData.map((visitID) => {
if (!uniqueVals.includes(visitID[0])) {
uniqueVals.push(visitID[0]);
}
});

Javascript - find all possible strings

Looking for some tips to solve this problem. We have string chain
const str = "543163431154",
and array with numbers where elements are basically numbers taken from this string
const array = ["21154", "543123", "163421154"]
What I'm looking for is to find all possible strings
Was thinking to split our input string as first, then create variable to store single letters. Subsequently I could iterate over newly created array in some kind of reduce function, but tbh I have no right solution
Here's an algorithm,
From your array, create 5 arrays, each one with different order of the elements from the original array
Iterate over each array
For each element, check using regex if the str starts with it (^currentElement)
If it is, remove from your str the current element and continue to the next element
If it's not, continue to the next array from the 5 you created
If you reach the last index of every array and str starts with it, add the current array to the results.
Here you go, now because it's not a code writing site and it's not a specific code question I wont write it for you - but the above algorithm will work for you.
Edit: After a bit more reading I understood the problem a bit better, and boy was this fun!
const str = "14316342115414321154"
const array = ["21154", "143", "21154143", "1634", "163421154"]
const findAllCombinations = (str, match) => {
const result = match.reduce((acc, layer) => {
if(str.indexOf(layer) === 0) {
if(str.substring(layer.length).length > 0) {
const nextLayer = findAllCombinations(str.substring(layer.length), match).map(c => addToLayer(layer, c))
acc.push(...nextLayer)
} else {
acc.push(addToLayer(layer, ""))
}
}
return acc;
}, [])
return result
}
const addToLayer = (layer, add) => `:${layer}${add}`
console.log(findAllCombinations(str,array))

filtering two knockout arrays to find the difference

I'm using knockout and have two arrays.
I want to find the difference between the arrays, i.e. any items that are in the longer array that are not in the smaller one.
i have
console.warn(items1); // 10
console.warn(items2); // 11
var filtered = ko.utils.arrayFilter(items1, function (e) {
return !items2.indexOf(e) > -1;
});
console.warn(filtered); // 10
How do I changes this to leave filtered with the 1 new item?
I've tried return items2.indexOf(e) > -1;
I've tried switching the arrays around on the filter and return.
I've tried return items2.indexOf(e) == -1;
All either give 10, 11, or 0.
How do I make it return 1?
You can get the difference by filtering the 2nd array for items that are not included in the first.
const difference = items2.filter(item => !items1.includes(item));
I would suggest using !includes as per the other answers, but for the sake of completeness this is how you would keep your approach if you want to:
var filtered = ko.utils.arrayFilter(items2, function (e) {
return !items1.indexOf(e) === -1;
});
ko.utils.arrayFilter will return items from the array you pass in as the first argument, and you want items from the longer array, so you should pass in items2. You want it to return items which are not in items1, so indexOf will return -1 for those items.
You can use filter to check for the difference for example
ar1=[1,2,3,4,5,7,8]
ar2=[2,10,9,1,2,3,4,5,7]
dif=ar2.filter(x=>!ar1.some(y=>x==y))
console.log(dif)
// or
dif=ar2.filter(x=>!ar1.includes(x))
console.log(dif)

Javascript: With an array of indices, splice a nested object using the indices to find the element with a recursive function

Lets say I have an array: [0,1,5].
The object I want to splice is object[0].content[1].content[5].splice()
However, the array can be however long, if it's just length 1,
then object[0].splice()
If it's length 2, object[0].content[1].splice()
I want to create a recursive function that does this, so I don't have to make a lot of if length conditionals. Any ideas on how to do this? Thank you
Recursion is neither necessary nor desirable for solving a problem of this type. All you need is a simple loop:
var array = [0, 1, 5];
var result = object[array.shift()];
while(var index = array.shift()) {
result = result.content[index];
}
var spliceResult = result.splice();
I get that recursiveness is not necessary in this situation. In the grand scheme neither is coding. But sometimes students like myself come to these places for help for specific questions based on constraints or edge cases. Try this one on for size. This specifically eliminates more than one occurrence of 0.
var takeOut = function(array) {
if (array.length === 0) { return array };
if(takeOut(array.slice(1))[0] === 0 && array[0] === 0) {
return takeOut(array.slice(1));
} else {
return [array[0]].concat(takeOut(array.slice(1)));
}
};

Splitting an array of numbers and non-numbers into two separate arrays

I'm very new to javascript and I'm trying to create a function that takes a mixed input of numbers and then loops through the array in order to sort them into two newer arrays so I can manipulate them further.
So if I have an input of
1,a,2,b,3,c,4,d,
I want to make two new arrays of
1,2,3,4 and a,b,c,d
So far I've been able to split the input string at the comma, so that I now have
1a2b3c4d
all I need to be able to do now is just separate the numbers and non-numbers. I was thinking of using two loops: one that checks
if(isNan.array[n] == True )
and then trying to find a way to store the letters into a variable using the loop and then using another loop to do so for the numbers using another if function.
Is this how I should do it, and do you have any advice on how to go about it?
Edit:
I now have this code to check for letters:
if (isNaN(splitResult[L])) {
for (i = 0; i < splitResult; i++) {
letterArray.add(splitResult[L]);
L = L + 1
When I try to output the results to a box to count letters (using the variable L), nothing shows up. I doubt I've made a new array
just for completion, split the string into array first :)
let yourString = '1a2b3c4d';
let yourArray = yourString.split('');
let letterArray = [];
let numberArray = [];
yourArray.forEach(item => {
if(isNaN(item) && typeof item === 'string'){
letterArray.push(item);
}
else if(!isNaN(item) {
numberArray.push(item);
}
});
console.log(letterArray, numberArray);
All you need to do is loop through the array, you can use the Array prototypes forEach. Or you can use the normal for loop to check through each element of the array. You can now check if each element isNaN and then push into the right array appropriately. You can use the snippet below
const yourArray = ['1','a','2','b','3','c','4','d'];
const letterArray = [];
const numberArray = [];
yourArray.forEach((eachItem) => {
if(isNaN(eachItem)){
letterArray.push(eachItem);
} else {
numberArray.push(eachItem);
}
});
console.log(letterArray, numberArray);

Categories

Resources