Shorthand for creating an array of string values in javascript - javascript

Is there a quick way to create a literal array filled with strings in javascript?
I am coming from Ruby, where using %w{} allows for you to omit quotation marks and commas around the values of the array. For example:
array = %w{a b c}
=> ["a", "b", "c"]
is equivalent to the standard syntax for literal assignment:
array = ["a", "b", "c"]
=> ["a", "b", "c"]
Is there anything similar to this in javascript?

There may be a better way, but this would work:
var array = 'abc'.split(''); // ['a', 'b', 'c']
And for words:
var array = 'domo arigato mr. roboto'.split(' ');
// ['domo', 'arigato', 'mr.', 'roboto']

I don't know it's a proper way or not but I go with
'abc'.split(''); //returns array

Related

create two differents variables from the same array [duplicate]

This question already has answers here:
Copy array by value
(39 answers)
Closed 3 years ago.
I've an array, and I want to create 2 differents variables from the same array but this variables must have different result. For example, an array of string : the first variable must contain this array, and the other variable must contains this values but sorted. But it's not working :
var letters = ['b', 'c', 'a']; // datas
const lettersUnsorted = letters; // i want the array like the var "letters"
const letterSorted = letters.sort(); // i want the array like the var "letters" but sorted
console.log(letterSorted); // OK => returns: ["a", "b", "c"]
console.log(lettersUnsorted); // KO => returns: ["a", "b", "c"] instead of ['b', 'c', 'a']
You should make a copy the array first because sort() method modifies the original array. You can make the copy of the array using slice()
var letters = ['b', 'c', 'a'];
const lettersUnsorted = letters;
const letterSorted = letters.slice().sort(); //this line is changed
console.log(letterSorted);
console.log(lettersUnsorted);
This is because the reference to the original letters array is maintained.
lettersUnsorted and letterSorted are both referencing to the letters variable. This is because letters is an array (which is technically an object), and in JavaScript, assigning another variable to it will result in assignment by reference (rather than assignment by value). Therefore, any operations or mutation to letters will result in both lettersUnsorted and letterSorted in having the same result as letters, due to the reference to letter.
You should create a shallow clone of the original letters array. This will allow you to safely carry out any mutation without affecting the other array. We can achieve this using ES6's spread syntax.
const letters = ['b', 'c', 'a'];
const lettersClone = [...letters].sort();
console.log(letters);
console.log(lettersClone);
you can use concat also.
var letters = ['b', 'c', 'a'];
const lettersUnsorted = letters;
const letterssorted = ([].concat(letters)).sort();

What is the purpose of spread syntax in this example? [duplicate]

This question already has answers here:
Why does spread syntax convert my string into an array?
(5 answers)
Closed 4 years ago.
Here,we created Hashmap with keys and value.Then we use array.map to get our result. i.e If we input "cat",we will get output as "dog".I didnt get how spread syntax is used.
var rule =
{
"c": "d",
"a": "o",
"t": "g",
"h": "a",
"e": "n",
"n": "t",
}
function output(str) {
return [...str].map(d => rule[d]).join('')
}
console.log(output('cat'))
Break it down:
[...str]
Gives: ['c', 'a', 't'];
In this case, the spread syntax breaks up the string into an array. Where each index represents a letter from the string.
.map(d => rule[d])
Converts the above array to:
['d', 'o', 'g']
As it goes through each value and uses the javascript object to get its value: (so 'c' maps to 'd' as rule['c'] = 'd', 'a' maps to 'o', etc...)
.join('')
Converts the above array to a string dog
Thus, doing:
console.log(output('cat'))
Gives: "dog"
spread syntax on a string turns it into an array consisting of its characters. This works because strings are iterable collections. http://es6-features.org/#SpreadOperator
In your case the spread operator spreads the string "cat" into an array of characters containing ['c','a','t']
Then it iterates over this array to provide the output string matches the values. There you get the string "dog" as output!
You would not be able to apply map to the string directly, as String does not have such a method. With the spread syntax you get an array of individual characters, and then map can be applied to that array.
It is in fact better practice to use Array.from instead, because it does not create the intermediate array and still allows you to execute a function on each character (using the second argument):
Array.from(str, d => rule[d]).join('')
It takes an iterable and returns each item of the iterable by using the spread syntax ....
In this case, a string is splitted to an array of characters.
['c', 'a', 't']
The same result could be achieved, if you use Array.from, which has a built-in mapping parameter.
var rule = { c: "d", a: "o", t: "g", h: "a", e: "n", n: "t" }
function output(str) {
return Array.from(str, d => rule[d]).join('');
}
console.log(output('cat')) ;

Replace in array using lodash

Is there an easy way to replace all appearances of an primitive in an array with another one. So that ['a', 'b', 'a', 'c'] would become ['x', 'b', 'x', 'c'] when replacing a with x. I'm aware that this can be done with a map function, but I wonder if have overlooked a simpler way.
In the specific case of strings your example has, you can do it natively with:
myArr.join(",").replace(/a/g,"x").split(",");
Where "," is some string that doesn't appear in the array.
That said, I don't see the issue with a _.map - it sounds like the better approach since this is in fact what you're doing. You're mapping the array to itself with the value replaced.
_.map(myArr,function(el){
return (el==='a') ? 'x' : el;
})
I don't know about "simpler", but you can make it reusable
function swap(ref, replacement, input) {
return (ref === input) ? replacement : input;
}
var a = ['a', 'b', 'a', 'c'];
_.map(a, _.partial(swap, 'a', 'x'));
If the array contains mutable objects, It's straightforward with lodash's find function.
var arr = [{'a':'a'}, {'b':'b'},{'a':'a'},{'c':'c'}];
while(_.find(arr, {'a':'a'})){
(_.find(arr, {'a':'a'})).a = 'x';
}
console.log(arr); // [{'a':'x'}, {'b':'b'},{'a':'x'},{'c':'c'}]
Another simple solution. Works well with arrays of strings, replaces all the occurrences, reads well.
var arr1 = ['a', 'b', 'a', 'c'];
var arr2 = _.map(arr1, _.partial(_.replace, _, 'a', 'd'));
console.log(arr2); // ["d", "b", "d", "c"]

Convenience method to get sub-indices of array in javascript

Is there a convenient way to get say the first n number of indices from this array:
var alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];
and store it in another array, say alphabet2 = ['a','b','c']; without having to brute force with a loop? Thanks
Use the slice method:
> var alphabet = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'];
> alphabet.slice(0,3)
["a", "b", "c"]

Join Array from startIndex to endIndex

I wanted to ask if there is some kind of utility function which offers array joining while providing an index. Maybe Prototype of jQuery provides this, if not, I will write it on my own :)
What I expect is something like
var array= ["a", "b", "c", "d"];
function Array.prototype.join(seperator [, startIndex, endIndex]){
// code
}
so that array.join("-", 1, 2) would return "b-c"
Is there this kind of utility function in an pretty common Javascript Library?
Regards
globalworming
It works native
["a", "b", "c", "d"].slice(1,3).join("-") //b-c
If you want it to behave like your definition you could use it that way:
Array.prototype.myJoin = function(seperator,start,end){
if(!start) start = 0;
if(!end) end = this.length - 1;
end++;
return this.slice(start,end).join(seperator);
};
var arr = ["a", "b", "c", "d"];
arr.myJoin("-",2,3) //c-d
arr.myJoin("-") //a-b-c-d
arr.myJoin("-",1) //b-c-d
Just slice the array you want out, then join it manually.
var array= ["a", "b", "c", "d"];
var joinedArray = array.slice(1, 3).join("-");
Note: slice() doesn't include the last index specified, so (1, 3) is equivalent to (1, 2).

Categories

Resources