Array of numbers to Array of one string - javascript

I need to [1, 2, 3] over to ['123'].
I must return [1, 2, 3] over to ['123'] while using an arrow function (no regex):
Must be used:
const functionOne = (arrayOne) => {
};
console.log(functionOne([1, 2, 3]));
So, I tried the following:
First, I created a string. This gave me 1,2,3
Then, I removed the commas, so, I could join the numbers. This gave me 123.
Finally, I tried to put back the number as a string into the array but this didn't work. This gave me ['1', '2', '3'] instead of ['123']. I think the .split method is what is wrong in my code but I cannot find another one (currently learning JavaScript).
const functionOne = (arrayOne) => {
let stepOne = arrayOne.toString(arrayOne => arrayOne.toString());
console.log(stepOne);
stepOne = stepOne.split(',').join('');
console.log(stepOne);
return stepOne.split('');
};
console.log(functionOne([1, 2, 3]));

You can join using "" as the delimiter (it will automatically convert the elements to strings as it produces the output string), then put the result in an array as its only element ([____]):
const functionOne = (array) => [array.join("")];
console.log(functionOne([1, 2, 3]));
Issues with your original approach:
Array's toString completesly ignores the argument you're giving it, instead using its default behavior of join(",").
Splitting it on , again just gives you back an array, but this time of strings.
Rejoining that with join('') does give you "123", but doesn't put it in an array.

You could take a recursive function.
const
fn = ([v, ...rest]) => rest.length
? [v + fn(rest)]
: [v];
console.log(fn([1, 2, 3]));

const functionOne = (arrayOne) => {
let stepOne = arrayOne.toString();
stepOne = stepOne.split(',').join('');
return [stepOne];
};
console.log(functionOne([1, 2, 3]));
The .toString() method will convert the array [1, 2, 3] to the string "1,2,3", then .split(',').join('') removes the commas and joins the numbers as a single string "123". Finally, return [stepOne]; returns the string "123" inside an array ['123'].

Related

filter and includes showing error message

can someone please explain to me why this is not working?
const numbers = [1, 2, 3, 4, 5];
const filtered = numbers.filter((num) => num.includes(1));
console.log(filtered);
I am getting this message saying num.includes is not a function.
.includes exists for two prototypes, Array.prototype.includes() and String.prototype.includes(), your array elements are of type number which has no such method
.includes() only works on strings or arrays. You are calling on a number. You want const filtered = numbers.filter((num) => num === 1)
var numbers = [1, 2, 3, 4, 5];
numbers=numbers.map(String);//changes elements to string
const filtered = numbers.filter((num) => num.includes(1));
console.log(filtered);
should fix the problem

Problem with Accesing array data Javascript

I want to access data of var a so it is: 245 but instead it only accesses the last one. so if i print it out it says 5
var A = [1, 2, 3, 4, 5];
var B = A[[1], [3], [4]];
console.log(B)
When accessing an object using square bracket notation — object[expression] — the expression resolves to the string name of the property.
The expression [1], [3], [4] consists of three array literals separated by comma operators. So it becomes [4]. Then it gets converted to a string: "4". Hence your result.
JavaScript doesn't have any syntax for picking non-contiguous members of an array in a single operation. (For contiguous members you have the slice method.)
You need to get the values one by one.
var A = [1, 2, 3, 4, 5];
var B = [A[1], A[3], A[4]];
console.log(B.join(""))
var A = [1, 2, 3, 4, 5];
var B = [A[1], A[3], A[4]];
console.log(B)
You'll need to access A multiple times for each index.
var A = [1, 2, 3, 4, 5];
var B = A[1];
console.log(A[1], A[3], A[4])
You can access them directly like that.
If you want to access index 2 for example, you should do console.log(A[1]);
You can't access multiple indices at the same time.
A variable can have only one value.
#Quentin solution resolve the problem, I wrote this solution to recommend you to create an array of index, and iterate over it.
Note: You are getting the last index, because you are using the comma operator. The comma operator allows you to put multiple expressions. The resulting will be the value of the last comma separated expression.
const A = [1, 2, 3, 4, 5];
const indexes = [1,3,4];
const B = indexes.map(i => A[i]).join``;
console.log(B);

Ramda: Confused about pipe

I'm learning functional programming in JS and I'm doing it with Ramda.
I'm trying to make a function that takes parameters and returns a list. Here is the code:
const list = R.unapply(R.identity);
list(1, 2, 3); // => [1, 2, 3]
Now I tried doing this using pipe:
const otherList = R.pipe(R.identity, R.unapply);
otherList(1,2,3);
// => function(){return t(Array.prototype.slice.call(arguments,0))}
Which returns a weird function.
This:
const otherList = R.pipe(R.identity, R.unapply);
otherList(R.identity)(1,2,3); // => [1, 2, 3]
works for some reason.
I know this might be a newbie question, but how would you construct f(g(x)) with pipe, if f is unapply and g is identity?
Read the R.unapply docs. It's a function that gets a function and returns a function, which can take multiple parameters, collect it to a single array, and pass it as the parameter for the wrapped function.
So in the 1st case, it converts R.identity to a function that can receive multiple parameters and return an array.
In the 2nd case, R.unapply gets the result of R.identity - a single value, and not a function. If you pass R.identity as a parameter to the pipe, R.unapply gets a function and return a function, which is similar to the 1st case.
To make R.unapply work with R.pipe, you need to pass R.pipe to R.unapply:
const fn = R.unapply(R.pipe(
R.identity
))
const result = fn(1, 2, 3)
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.26.1/ramda.min.js"></script>
It looks as though you really are thinking of pipe incorrectly.
When you use unapply(identity), you are passing the function identity to unapply.
But when you try pipe(identity, unapply), you get back a function that passes the results of calling identity to unapply.
That this works is mostly a coincidence: pipe(identity, unapply)(identity). Think of it as (...args) => unapply(identity(identity))(...args). Since identity(identity) is just identity, this turns into (...args) => unapply(identity)(...args), which can be simplified to unapply(identity). This only means something important because of the nature of identity.
You would use unapply to transform a function that would normally take its arguments as an array into a function that can take any number of positional arguments:
sum([1, 2, 3]); //=> 6
unapply(sum)(1, 2, 3) //=> 6
This allows you to, among many other things, map over any number of positional arguments:
unapply(map(inc))(1, 2) //=> [2, 3]
unapply(map(inc))(1, 2, 3) //=> [2, 3, 4]
unapply(map(inc))(1, 2, 3, 4) //=> [2, 3, 4, 5]
identity will always return its first argument. So unapply(identity)(1,2) is the same as identity([1,2]).
If your end goal was to create a function that returns a list of its arguments, I don't think you needed pipe in the first place. unapply(identity) was already doing that.
However, if what you need to do is to make sure that your pipe gets its parameters as a list, then you simply need to wrap pipe with unapply:
const sumplusplus = unapply(pipe(sum, inc, inc));
sumplusplus(1, 2, 3); //=> 8

Is there a way to apply multiple Array methods to an array in 1 line?

In the simple test code below I push the number 10 into an array and then splice 'hello world' into the array on the 2nd index. It works as expected.
"use strict";
let myArray = [1, 2, 3, 4, 5];
myArray.push(10);
myArray.splice(2, 0, 'hello world');
console.log(myArray);
However is it possible to do this on one line? I tried chaining in the example below and it throws an error. I can't find anyone talking about this online.
"use strict";
let myArray = [1, 2, 3, 4, 5];
myArray.push(10).splice(2, 0, 'hello world');
console.log(myArray);
Yes, it is possible to do it in one line.
"use strict";
let myArray = [1, 2, 3, 4, 5];
myArray.push(10); myArray.splice(2, 0, 'hello world');
console.log(myArray);
But why do you want to do that in one line? If your concern is readability I would stick with two lines. If you want it more functional, then use a functional library
edit
I agree with what every one else said about chainability. I'm just trying to make another point
These built-in methods are not designed to be part of a fluent interface, as they don't return the array that they're operating on (push() returns the new length, splice() returns the sub-array that was removed). You could add your own methods that are similar but are fluent.
Array.prototype.mypush = function(...args) {
this.push(...args);
return this;
};
Array.prototype.mysplice = function(...args) {
this.splice(...args);
return this;
}
let myArray = [1, 2, 3, 4, 5];
myArray.mypush(10).mysplice(2, 0, 'hello world');
console.log(myArray);
If you're using a modern JavaScript browser the push part is a little easier, using the array spread syntax. Since everyone else is using chaining (which requires altering the built-in Array object, which I don't like), I'll use something different:
"use strict";
let myArray = [1, 2, 3, 4, 5];
function notSplice(array, start, end, ...items) {
array.splice.apply(array, [start, end, ...items]);
return array;
}
myArray = notSplice([...myArray, 10], 2, 0, 'hello world');
console.log(myArray);
You could take the methods and parameters in an array and iterate with a function, which take the array as this value.
"use strict";
function arrayFn([k, ...a]) { this[k](...a); }
let myArray = [1, 2, 3, 4, 5];
[
['push', 10],
['splice', 2, 0, 'hello world']
].forEach(arrayFn, myArray);
console.log(myArray);
Chaining works by calling a method of the return value of the previous method call. For example:
myArray.filter(...).map(...).join(', ').trim()
// is equivalent to
const filteredArray = filtered.map(...)
const mappedArray = filteredArray.map(...) // filteredArray is an array, we can use map.
const aString = mappedArray.join(', ') // mappedArray is an array, we can use join
const trimmedString = aString.trim() // aString is a string, we can use trim
But in your case, it doesn't work because push returns a number (the length of the array plus the new item). There is no splice method for numbers.
myArray.push(...).splice(...)
// is equivalent to doing
const result1 = myArray.push(...)
const result2 = result1.splice(...) // But result1 isn't an array.
This is only possible if the methods you want to chain all return an Array, push returns the length of the array:
console.log([1,2].push(3)) // 3, not an array
console.log([1,2].map(x => x+1)) // [2,3], an array

using array.map with repeat in Javascript

Hello I have the following:
var a = [1, 2, 3]
I would like to update this array to:
a = [11,22,33]
I am trying to do something like
a.map(repeat(2));
but it results in an error.
I know I could easily loop through this, but I am trying to practice using more concise code, and expand my knowledge a bit on different functions, and how to use them.
Is something like this possible?
You could convert the number to string, repeat the value and convert it back to number.
var a = [1, 2, 3]
a = a.map(a => +a.toString().repeat(2));
console.log(a);
Given that you seem to be looking for repeating the digits, use strings for that. Which have a handy repeat method for this purpose:
a.map(x => Number(String(x).repeat(2))));
If you want to use your notation, you need to make a higher-order repeat function that returns another function to be used as the map callback:
function repeat(times) {
return x => String(x).repeat(times);
}
a.map(repeat(2)).map(Number)
Yes that is possible. You can define repeat as a function that returns a function:
function repeat(times) {
return function (value) {
return +String(value).repeat(times);
}
}
// Your code:
var a = [1, 2, 3];
var result = a.map(repeat(2));
console.log(result);
The map method expects a function as argument, so the call to repeat(2) should return a function. That (inner) function uses String#repeat after converting the value to string, and then converts the result back to number with the unary +.
Here you go, number version and string version
const doubleIt = n => Number(`${n}${n}`);
const arr = [1, 2, 3, 55];
const strArr = arr.map(o => `${o}${o}`);
const numArr = arr.map(o => o * 11);
const numFromStringsArr = arr.map(o => doubleIt(o));
console.log(strArr);
console.log(numArr);
console.log(numFromStringsArr);
You can create an array of N .length with Array(), use Array.prototype.fill() to fill the created array with current element of .map() callback, chain Array.prototype.join() with "" as parameter, use + operator to convert string to number
var a = [1, 2, 3], n = 2;
a = a.map(el => +Array(n).fill(el).join(""));
console.log(a);
Simply, try it with Array join() method:
a.map(x => Array(2).join(x));

Categories

Resources