I have an array of values:
let myArray = [ 'Ifmanwas',
'meanttos',
'tayonthe',
'groundgo',
'dwouldha',
'vegivenu',
'sroots' ]
I want to print out a new value for each item in the array so that the first item is a collection of all the characters at the zero index, the second is a collection of all the characters at the 1 index position, ect...
So for instance, the output of the first array would be "Imtgdvs" (all the letters at ("0"), the second would be "fearwer" (all the letters at index "1") ect...
I am very lost on how to do this and have tried multiple different ways, any help is appreciated.
For this simple attempt I have created an array of all the letters for the first instance:
function convertToCode(box) {
let arr = [];
for (i = 0; i < box.length; i++) {
let counter = i;
let index = box[counter];
let letter = index.charAt(0);
arr.push(letter);
}
console.log(arr);
}
convertToCode(myArray)
Thanks
The main issue in your example is this: index.charAt(0);. This will always get the first character, whereas you need a nested loop.
You could use Array.map() in combination with Array.reduce(), like so:
let myArray = ['Ifmanwas','meanttos','tayonthe','groundgo','dwouldha','vegivenu','sroots'];
const result = Array.from(myArray[0]) //Create an array as long as our first string
.map((l,idx) => //Update each item in that array...
myArray.reduce((out,str) => str[idx] ? out+str[idx] : out, "") //to be a combination of all letters at index [idx] from original array
);
console.log(result);
Note that this uses the first string in the array to decide how many strings to make, as opposed to the longest string.
Related
Consider this:
var longestCommonPrefix = function(strs) {
strs.forEach((item, index) => {
let splitArr = item.split('');
console.log('split array item is: ' + splitArr)
});
};
longestCommonPrefix(["flower","flow","flight"])
https://leetcode.com/problems/longest-common-prefix/
I need to compare these arrays to find the common prefix in them. So the output of this code at the ends needs to be:
common prefix is: "fl"
As of right now the output of the above code block is this
split array item is: f,l,o,w,e,r
split array item is: f,l,o,w
split array item is: f,l,i,g,h,t
I need to either
Loop by each character and array so the output is something like:
f,f,f,l,l,l,o,o,i,w,w,g,e,,h,r,,t
I tried to do this like this:
Looping Through an Array of Characters
You might want to take a look at the String's split method.
So I am already doing that, and my thought process is now this:
lets get our arrays, iterate over each character, and then make a new master array where we can count each instance of a letter appearing 3 times and print out that character, in order to get our common prefix.
So now that approach is this:
var longestCommonPrefix = function(strs) {
// establish the new array
// we need this for later, outside our loop so we can have a giant array to sort/look at/count
let charArray = [];
// loop through each array
strs.forEach((item, index) => {
// split the array by character
let splitArr = item.split('');
// test console log
console.log('split array item is: ' + splitArr)
// iterate over each character, and push it into a new array
splitArr.forEach((letter, index) => {
charArray.push(letter)
});
});
// log final array
console.log('FINAL ARRAY IS...: ' + charArray)
};
longestCommonPrefix(["flower","flow","flight"])
So we're getting closer because we're now here:
FINAL ARRAY IS...: f,l,o,w,e,r,f,l,o,w,f,l,i,g,h,t
But we're not quite there with what we want, f,f,f,l,l,l,o,o,i,w,w,g,e,,h,r,,t
We need to somehow sort the array by matching character, I think...?
When we do charArray.sort() we get this:
"FINAL ARRAY IS...: e,f,f,f,g,h,i,l,l,l,o,o,r,t,w,w"
Not quite...
Here are some SO answers based on my google search keyword "sort array by matching characters" that kind of talk about it but aren't quite relevant to my question
Javascript sort an array by matching to string
Sort an array of strings based on a character in the string
What keyword/search should I have used to find the results?
How can I sort this array from e,f,f,f,g,h,i,l,l,l,o,o,r,t,w,w to f,f,f,l,l,l,o,o,i,w,w,g,e,,h,r,,t ... ?
Here's a possible solution, needs to cover cases with an empty array but you get an idea.
While all letters at index c are the same I keep looping, otherwise I exit.
At the end I take c characters from the first word as it's the length of the common prefix.
function longestCommonPrefix(strs) {
var splits = strs.map((item) => item.split(''));
var c = 0;
var matches = true;
while (matches) {
var letter = splits[0][c];
if (letter != null) {
matches = splits.every(s => s[c] == letter);
if (matches)
c++;
} else matches = false;
}
var prefix = strs[0].slice(0, c);
console.log("The prefix is: " + prefix);
};
longestCommonPrefix(["flower", "flow", "flight"])
Hello i would like to create something for sort args in the list by how many times they are in the list
all arguments are separated with one ;
let list = "abcd1; abcd4; abcd4; abcd9; abcd2; abcd5"
the list can be 5 args long like 100 or 243.
i think it can work with two for loops one to see if the i element is duplicated and compare the array[i] with the array[j] and you could use a temporary array to create the object then later reassign to the main array.
but don't know how to do it.
Your list
let list = "abcd1; abcd4; abcd4; abcd9; abcd2; abcd5"
Create a new list by splitting the string at ';'
let newList = list.split(';')
// newList = ["abcd1", " abcd4", " abcd4", " abcd9", " abcd2", " abcd5"]
Declare an empty object and iterate through all elements of new list and add them as keys to the object. Set the value as 1 if the key is not present in the object, else add 1 to the value if key is present.
let obj = {}
for (let i of newList) {
let newI = i.trim() // trim() to remove spaces or new line characters
// check if newI is already present in the object, i.e. we've seen it before
// if that's the case then it must have a value so increment that value by 1
if (newI in obj) {
obj[newI] += 1
}
// if newI is not present in the object then we're seeing it for the first time.
// so set its value as 1
else {
obj[newI] = 1
}
}
// obj = {abcd1: 1, abcd4: 2, abcd9: 1, abcd2: 1, abcd5: 1}
Get the keys of the object in an array and finally sort that array while sending the value in the object ``obj``` as comparison parameter. As we want to sort by how many times that value appears in the string.
let arr = Object.keys(obj)
// arr = ["abcd1", "abcd4", "abcd9", "abcd2", "abcd5"]
arr.sort((a, b) => obj[a] - obj[b])
// arr = ["abcd1", "abcd9", "abcd2", "abcd5", "abcd4"]
Sorted from least number of appearances in string to maximum number of appearances
I want to sort an array of phone numbers and have the length of the array outputted based on areacode. For example:
var nums = [
8881756223,
8881742341,
9187221757,
...,
]
there are a lot more entries than that (roughly 1300) and its already in numerical order. However, what I want it to do is:
1. look at the first 3 numbers of the first entry
2. look at the next entries first 3 numbers
3. if they are different, then splice the array, console.log new array.length
and console.log that area code
so for example, the first two numbers in the array i provided will be spliced into their new array, and the console output will be:
areacode: 888, length: 1
areacode: 918, length: 0
I know the regex to search for the first the numbers, but I don't exactly know how to splice them into their own arrays...Like i know, use splice, but comparing the two with logic statements, I've never had to do something like that before while using a regular expression.
what I have so far is this:
const patt = new RegExp('^\d{3}')
var newArr = nums.filter(x => patt)
for (var i = 0; i < newArr.length; i++)
console.log(newArr[i])
but this is spitting out the full number, not the area code its self. Of course ill be adding the logic to sort after i get it to just spit out area codes.
I suggest using
nums.map(x => ("" + x).replace(/^(\d{3})[^]*/, '$1'))
Here,
"" + x will coerce the number to string
.replace(/^(\d{3})[^]*/, '$1') will remove all chars keeping the first 3 digits (or the whole string upon no match).
JS Demo:
var nums = [
8881756223,
8881742341,
9187221757,
1
];
var res = nums.map(x => ("" + x).replace(/^(\d{3})[^]*/, '$1'));
console.log(res);
you can try this
var nums = [
8881756223,
8881742341,
9187221757
]
var prefixes = nums.map(x=>(x+"").substr(0,3));
var votes = prefixes.reduce(
(votes, curr) => {
if(votes[curr]) votes[curr]++;
else {votes[curr] =1;}
return votes;
}, {});
var ans = Object.keys(votes).map(x => ({areacode:x, length:votes[x]}));
console.log(ans);
ans will hold the value you require
vote counting technique i used is explained here https://igghub.github.io/2017/01/15/useful-js-reduce-trick/
When looking at set of characters I am trying to put each letter into a specifc order in an array. For Example: Given the Strings "cat" and "dog" I would want an array that contains [d,o,g,c,a,t], cat at the end of the array because it was read first.
Currently I have tried this:
However, when I try the code below assuming the strings are "cat" and "dog".
I get an array containing: [c,a,t,d,o,g]. Instead of push I have also tried .unshift but the array now reads: [g,o,d,t,a,c].
var chars = /^[a-z]$/;
var string = [];
function makeword(){
if(currentChar.match(chars)){
string.push(currentChar);
currentChar = getNextChar(); //Gets next Character in the String
makeword();
}
}
Is something like this possible in Javascript?
If I understood you correctly, you want to provide a list of strings, then have them show up in an array in reverse order, with each letter as an element of the array. The following function will do just that:
function makeWords() {
var arr = [];
for(var i = arguments.length - 1; i >=0; i--) {
arr.push(arguments[i]);
}
return arr.join('').split('');
}
so running makeWords('cat', 'dog') will result in ['d','o','g','c','a','t'].
It's a relatively simple code when a functional approach is used. The rest and spread operators are very handy both to collect the function arguments and to spread the characters of a word into an array.
var characterify = (...c) => c.reduceRight((a,b) => a.concat([...b]) ,[]);
document.write("<pre>" + JSON.stringify(characterify("cat","dog")) + "</pre>");
Got a string that is a series of 0 or 1 bit and an array of values, if in the string are characters that are set to 1, I need to return the corresponding value from the array.
example: mystring = "0101"; myarray =["A","B","C","D"]; then result = "B,D"
how can I get this result?
for(var i=0;i<mystring.length;i++){
if(mystring[i] != 0)
{
result = myarray[i];
}
}
Your code seems to work just fine, so you can just add another array and push the values on to that:
var result = [];
for (var i = 0 ...
result.push(myarray[i]);
http://jsfiddle.net/ExplosionPIlls/syA2c/
A more clever way to do this would be to apply a filter to myarray that checks the corresponding mystring index.
myarray.filter(function (_, idx) {
return +mystring[idx];
})
http://jsfiddle.net/ExplosionPIlls/syA2c/1/
Iterate through the characters in the binary string, if you encounter a 1, add the value at the corresponding index in the array to a temporary array. Join the temporary array by commas to get the output string.
I am not really sure if this is what you are looking for, but this returns the array of matches.
var result = [];
for(var i=0;i<mystring.length;i++){
if(parseInt(mystring[i]) !== 0 ) {
result.push(myarray[i]);
}
}
return result;
result = new Array();
for(var i=0;i