How can I create a string that lists out numbers? - javascript

I am trying to make a string that lists out the dates of a month. For example, I need to make a string that lists out:
dayInDateOfBirthInput: "Day\n1\n2\n3\n4\n5\n6\n7\n8\n9\n10\n11\n12\n13\n14\n15\n16\n17\n18\n19\n20\n21\n22\n23\n24\n25\n26\n27\n28\n29\n30\n31",
I've tried doing this
[Array(31).keys()].map(x => x+1).join("\n")
Thanks for looking!

I've tried doing this [Array(31).keys()].map(x => x+1).join("\n")
You are very close. .keys() returns an Array Iterator object. You need to spread it to create an array.
console.log(
[...Array(31).keys()].map(x => x+1).join("\n")
)

Your code from the comments can be tweaked:
Array(31).fill(0).map((_,x) => x+1).join("\n");

Something like
const str = 'Day' + Array(31).fill(0).map((x, i) => `\n${i+1}`).join('');
console.log(str);

As others have pointed out, your example is missing a spread operator.
Might I suggest using Array.from(...) (of which the second argument is a map function):
let result = Array.from({length:31}, (_,i) => i+1).join("\n");
console.log(result);
let resultWithDay = `Day\n${result}`;
console.log(resultWithDay);
To reverse it:
let result = Array.from({length:31}, (_,i) => i+1).reverse().join("\n");
console.log(result);
let resultWithDay = `${result}\nDay`;
console.log(resultWithDay);

Related

Javascript join array with brackets

In javascript I need to join an array into a string with brackets. For example ['abc', 'yte', 'juu'] => (abc)(yte)(juu). I need the fastest and cleanest way to do this. I tried using the array join operator but it doesnt work on the first and last element.
You can do it with template literals. Use join() with )( separator, and wrap the result with ():
const data = ['abc', 'yte', 'juu'];
const result = `(${data.join(')(')})`;
console.log(result);
Thinking "I need the fastest and cleanest way to do this." is often not ideal. In most cases what people want is the most readable and understandable way to implement a solution.
I quite like the following. Where we first bracket each item in the array with map and then join the items with no delimiter:
const data = ['abc', 'yte', 'juu'];
let brackets = data.map(x => "(" + x + ")");
let result = brackets.join("")
console.log(result);
That of course takes two passes over the array. If you really must have the fastest solution just use a for loop:
const data = ['abc', 'yte', 'juu'];
let result = "";
for (let item of data) {
result += "(" + item + ")";
}
console.log(result);
In order to reduce an array to a single value (be that an object, array, string, number, ...) Javascript has the Array.prototype.reduce method, which achieves the desired result in a single loop and line:
console.log(['abc', 'yte', 'juu'].reduce((a,v)=>`${a}(${v})`,''))
const list = ['abc', 'yte', 'juu'];
const result = list.map(value => `(${value})`).join("");
console.log(result);

Need to modify array as per specific requirement in javascript

So I am working in typescript where I need to modify an array to some specific pattern.
Here is my array:
["sunday","monday","tuesday"]
This is what I need it to be like:
["day:Sunday","day:Monday","day:Tuesday"]
I have already tried map method like this:
result = arr.map(x => ({day: x}));
But map gives me result some different which is not needed:
[{"day":"sunday"},{"day":"monday"},{"day":"tuesday"}]
You're trying to prepend the strings and to change the first letter to upper:
const arr = ["sunday","monday","tuesday"];
const result = arr.map(x => 'day:' + x[0].toUpperCase() + x.slice(1));
console.log(result);
The problem is that you are adding those brackets, here's a solution:
const original = ["sunday","monday","tuesday"]
console.log(original)
const result = original.map(day => `day:${day}`);
console.log(result)
//["day:sunday", "day:monday", "day:tuesday"]
Array map is the right method, you just need to return a string, not an object:
result = arr.map(d => `day:${d.toUpperCase()}`)
const days = ["sunday","monday","tuesday"];
const dayFun = days.map((day) => {
const dayUppercase = day.charAt(0).toUpperCase() + day.slice(1);
return `day:${dayUppercase}`;
});
console.log(dayFun);

Sorting string values js

I have an array that looks like this:
0123456789123456:14
0123456789123456:138
0123456789123456:0
Basically I need to sort them in order from greatest to least, but sort by the numbers after the colon. I know the sort function is kind of weird but im not sure how I would do this without breaking the id before the colon up from the value after.
Split the string get the second value and sort by the delta.
const second = s => s.split(':')[1];
var array = ['0123456789123456:14', '0123456789123456:138', '0123456789123456:0'];
array.sort((a, b) => second(b) - second(a));
console.log(array);
Assuming the structure of the items in the array is known (like described), you could sort it like this.
const yourArray = ['0123456789123456:14', '0123456789123456:138', '0123456789123456:0'];
yourArray.sort((a, b) => (b.split(':')[1] - a.split(':')[1]));
console.log(yourArray);
You can use sort() and reverse(), like this (try it in your browser console):
var arrStr = [
'0123456789123456:14',
'0123456789123456:138',
'0123456789123456:0'
];
arrStr.sort();
console.log(arrStr);
arrStr.reverse();
console.log(arrStr);
You can use below helper to sort array of strings in javascript:
data.sort((a, b) => a[key].localeCompare(b[key]))

remove duplicates from array in moment js

i have
let array = [moment('2019-01-17'),moment('2019-01-19'),moment('2019-01-19'),moment('2019-01-21')];
i need to remove duplicates
so i written filter but it is not working correctly
array= array.filter((v,i) => !moment(array.indexOf(v)).isSame(moment(i)))
working live plunker code inside index.html
You were on the right track, but details were a bit off. Please try this:
const comparisonValues = array.map(v => v.valueOf());
array = array.filter((v,i) => comparisonValues.indexOf(v.valueOf()) == i);
Explanation:
array.filter((value, index, self) => self.indexOf(value) == index) is an useful pattern for finding unique values in an array
The intuition behind the pattern is to "pick only first instances of a value in an array"
It only works for values that can be directly compared - indexOf uses strict equality check internally (===)
momentValue.valueOf() will return an useful value for this comparison, namely number of milliseconds since the Unix Epoch
Our solution uses a helper array that consists of the millisecond values from valueOf and in filter, makes comparisons using valueOf() of the current value in iteration
Another way, if you want to use isSame, could be like this:
array = array.filter((v, i) => {
return array.findIndex(candidate => v.isSame(candidate)) == i
});
You can achieve the same result and faster with just a single Array.reduce and once you got the items grouped just get them via Object.values. This would be faster than for each items searching the entire array every time. For small arrays it would not matter but for larger it would be quite noticeable.
Here is the concise version:
let data = [moment('2019-01-17'), moment('2019-01-19'), moment('2019-01-19'), moment('2019-01-19'), moment('2019-01-19'), moment('2019-01-21')];
const result = data.reduce((a, c) => (a[c.format()] = c, a), {})
console.log(Object.values(result))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
And here the detailed one:
let data = [moment('2019-01-17'), moment('2019-01-19'), moment('2019-01-19'), moment('2019-01-19'), moment('2019-01-19'), moment('2019-01-21')];
const result = data.reduce((accumulator, current) => {
accumulator[current.format()] = current
return accumulator
}, {})
console.log(Object.values(result))
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>

Access multiple characters using bracket notation?

I'm returning the 2nd, 3rd and 5th numbers in the string '123456' by using
function returnSome(numbers) {
return numbers[1] + numbers[2] + numbers[4]
}
returnSome('123456'); //2, 3, 5
Simple enough right? What I'm wondering is whether there is a shorter way to write that out? something like numbers[1][2][4]?
I can't seem to find an answer online! (It may well be that I just don't know the correct terminology!)
Not really shorter, but you could use an array of indices and map that to the strings characters, then join them to a new string:
[1, 2, 4].map(i => numbers[i]).join("")
something like numbers[1][2][4]?
We can get quite close with currying:
const wrap = (str, res = "") => index => index + 1 ? wrap(str, res + str[index]) : res;
wrap(numbers)(1)(2)(4)()
You can turn the indices you want into a string that you iterate over and pull out from the array you pass in.
let returnSome = (numbers, sections) => sections.split("").map(i => +numbers[i]);
let returnSome = (numbers, sections) => sections.split("").map(i => +numbers[i]);
console.log( returnSome('123456', '124') ); //2, 3, 5

Categories