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

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

Related

Iterate over two separate arrays of different length and populate a third using a condition in JavaScript?

I've done something similar in the past with a nested loop, but for some reason I can't get my mind around this to get it to work. I keep running into problems that involve indexing of two separate arrays and it's been a continual stumbling block
In this case, I'm trying to sort a string. The string includes letters and numbers, the task is to sort the letters in reverse alphabetical order while keeping the numbers at their same index.
I've come up with this solution (probably not the most efficient), but can't get the sortString array to come together so that I can join the letters and numbers back into a string.
function reverse(str) {
// split the str into an array
const arr = [...str]
// converts each element in arr to a number, letters are string 'NaN'
const numArray = arr.map(x=> Number(x)).map(x=> x >= 0 ? x : String(x))
// array of the sorted letters
const letters = arr.filter(x=> !/[0-9]/g.test(x)).reverse()
// initiate empty array to hold the combined numbers and letters
let sortString = []
// Use for loop to cycle through and replace elements that are 'NaN' with letters from the letter array. All pushed to sortString.
for (let i=0; i<arr.length; i++) {
sortString.push(numArray[i] === 'NaN' ? letters[0] : numArray[i])
}
return sortString
}
reverse("ab89c") // output should be "cb89a"
You could get an array of non digits, sort it and map the splitted string with the sorted letters in places if not a digit.
const
reverse = string => {
const
array = Array.from(string),
letters = array
.filter(v => /\D/.test(v))
.sort();
return array
.map(v => /\D/.test(v) ? letters.pop() : v)
.join('');
};
console.log(reverse("ab89c"));
A slightly different approach takes a Proxy for the wanted items of sorting:
How to sort only part of array? between given indexes
Here's code that works:
Explanation of how the code works is in-line as comments.
Basically it takes the numbers out, sorts the letters in reverse, and puts the sorted letters back in the right place.
Because it's step-by-step, you could add console log on each variable after it's assigned to see how it works step by step.
function reverse(input) {
// This function from: https://stackoverflow.com/a/32567789/569302
function testIsLetter(c) {
return c.toLowerCase() != c.toUpperCase();
}
// Convert from array to string to process character by character
let inputAsArray = input.split('');
// This is where we'll lookup where to put the letters when we're done
let mapped = inputAsArray.map((s) => {
return {
s,
isLetter: testIsLetter(s)
}
})
// Now that we've captured where the letters are, take the numbers (non-letters) out
let filtered = mapped.filter(m => m.isLetter)
// Convert the object into just letters so they're easily compared when we sort
let filteredAsLettersArray = filtered.map(f => f.s)
// Sort ascending
filteredAsLettersArray.sort()
// Reverse to sort descending
filteredAsLettersArray.reverse()
// Now we need to put the letters back.
let resultAsArray = [];
let letterIndex = 0;
mapped.forEach(m => {
// If it's a letter, we use the sorted result (incrementing letterIndex each time)
if (m.isLetter) {
resultAsArray.push(filteredAsLettersArray[letterIndex]);
letterIndex++;
} else {
// Otherwise we use the number
resultAsArray.push(m.s);
}
});
let result = resultAsArray.join('');
return result;
}
console.log(reverse("ab89c"));
console.log(reverse("1a2eb8f9c"));

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))

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

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
}

Finding the Anagrams of a word from a list- codewars question

I am pretty new to programming and I was solving a problem on code wars which is as follows:
Question:
Write a function that will find all the anagrams of a word from a list. You will be given two inputs a word and an array with words. You should return an array of all the anagrams or an empty array if there are none.
This is my code
function anagrams(word, words) {
let word_Array = word.split('').sort()
let total = []
for (x = 0; x<words.length; x++) {
if(words[x].split('').sort() === word_Array) {
total.push(words[x])
} return total
}
}
The result should look something like this
anagrams('abba', ['aabb', 'abcd', 'bbaa', 'dada']) => ['aabb', 'bbaa']
I keep getting an empty array when I run my code. Please can someone tell me the error in my code. Thank you
Please take a look at the following snippet.
const sort = (word) => word.split('').sort().join('');
function anagrams(word, words) {
let token = sort(word);
let total = []
for (let x = 0; x < words.length; x++) {
if (sort(words[x]) === token) {
total.push(words[x])
}
}
return total
}
console.log(anagrams('abba', ['aabb', 'abcd', 'bbaa', 'dada']));
You are on the right track but missed a few details.
As others have mentioned you cant just compare discrete arrays with ===. The best you can do is an element wise compare. You dont really need to this if you compare normal value types such as numbers, strings, bools, ect. If you join the sorted string back its much easier to compare using built in operators such as ===.
Your control logic is wrong. Notice how you are returning straight from the loop? It means that at most you would ever get one results since the loop cant iterative over the full loop condition.
You should always qualify your variable declarations with let/const. This was missing in the for loop and would declare x as a global.
Improvements
You could replace the for loop with a for of and not have to worry about indexing.
for (let w of words) {
console.log(w); // we no longer have to worry about words[i].
}
Even better you could replace the entire for and array.push logic with a simple array.filter
const sort = (word) => word.split('').sort().join('');
function anagrams(word, words) {
let token = sort(word);
return words.filter((w) => sort(w) === token);
}
console.log(anagrams('abba', ['aabb', 'abcd', 'bbaa', 'dada']));
Array is Object in JavaScript, which is reference type.
So you can not use "===" to check whether two arrays are equals.
For example:
var array1=[1,2];
var array2=[1,2];
var result = array1 === array2;
the result will be false.
My suggestion is writing a new function to check whether two arrays are equals by comparing the items.
function areEquals(array1, array2){
if(array1.length!==array2.length){
return false;
}
for(var i in array1){
if(array1[i]!==array2[i]){
return false;
}
}
return true;
}

Categories

Resources