I have
var myArray = ["word", "are", "tame"];
var result = myArray.join('s').split('a');
1)computed: "wordsarestame"
2)computed: "words", "rest", "me"
My question is for the first computed,
computed: "wordsarestame"
why don't you add a 's' at the end of me? since it's .join('s') on whole myArray
You're joining 3 things, so you get 2 s in between. It's the same as doing:
var joined = "word" + "s" + "are" + "s" + "tame"
Array.join joins the elements of the array - it means it puts a glue element between each two array elements in succession. That's why you don't have it neither at the beginning of joined string, nor at the end of it.
Join combines the array into a string, and uses the provided string as the glue that holds them together. You don't need to glue anything at the end of the last string, so no more glue is applied:
var arr = [1, 2, 3];
console.log(arr.join('x'));
You could use map() to get your desired result:
var arr = [1, 2, 3];
console.log(arr.map(str => str + 'x').join(''));
Array.prototype.join()
manual
The join() method joins all elements of an array (or an array-like
object) into a string.
It glue each element of array elements. If you want to add a after theme, add another '' element of the array, then ues join().
var myArray = ["word", "are", "tame"];
myArray.push('');
console.log(myArray.join('s'));
Related
I'm having issues with some code. I'm trying to add an element to the end of a 2d array, but the log is returning the length of the array.
var arr = [["a"],["b"],["c"],["d"]];
var arr2 = arr.push(["e"]);
Logger.log(arr2);
arr2 is returning "5" but would like it to return the array with the pushed element at the end of this array.
Values will be pushed in the same memory reference, return type of push method is integer, (length of the array)
Please do like this, your results will be achieved
var arr = [["a"],["b"],["c"],["d"]];
arr.push(["e"]);
Logger.log(arr);
The push() method adds one or more elements to the end of an array and returns the new length of the array, so you just need to log the initial array.
var arr = [
["a"],
["b"],
["c"],
["d"]
];
arr.push(["e"]);
console.log(arr);
I need your help since i'm stuck at the challenge from checkio.
What am i missing? I get back:
Your result:"one,two,three"
Right result:"one,three,two"
The Challenge:
You are given two string with words separated by commas. Try to find what is common between these strings. The words are not repeated in the same string.
Your function should find all of the words that appear in both strings. The result must be represented as a string of words separated by commas in alphabetic order.
UPDATE
this is my code:
function commonWords(first, second) {
const firstWord = first.split(',');
const secondWord = second.split(',');
let match = firstWord.filter(value => secondWord.includes(value));
return match.toString()
}
match.toString() doesn't change the value of match variable. You need to return it from the function.
function commonWords(first, second) {
const firstWord = first.split(',');
const secondWord = second.split(',');
let match = firstWord.filter(value => secondWord.includes(value));
return match.toString()
}
Explanation
There are two kinds of methods.
Mutator Methods
The first kind changes the original variable. You don't need to reassign the variable in case of those methods. Some of them are reverse(), fill(), etc
Note: These methods are only for reference type(objects, array) not for value types(string, number, boolean).
const arr = [1, 2, 3, 4];
arr.reverse();
console.log(arr); //[4, 3, 2, 1]
Accessor Methods
The second type are those methods which doesn't change the original variables but it returns are new value which is used by assigning it to a variable using =.
Some of them are map(), filter() etc.
let arr = [1, 2, 3, 4];
arr.map(x => x * x); //This line has no impact at all
console.log(arr) //Nothing is changed
arr = arr.map(x => x * x); //This line changes 'arr'
console.log(arr); //[1, 4, 9, 16]
Now toString() is of second type(accessor method) type. Just calling that method never changes the original variable. You need to reassign or return according to your needs
I have JavaScript multidimensional array like this:
a 1
b 2
c 3
I want it converted into comma separated value like this:
function reg() {
var result = [];
var comma_value;
for (var i = 0; i < arrc.length; i++) {
if (parseInt(arrc[i].value)) {
result.push([arrp[i].value, arrc[i].value]);
}
// result is an array
// My desired result:
// comma_value = "a,1;b,2;c,3"
}
$('#str').val(JSON.stringify(result));
console.table(result);
console.log(result.join(', '));
}
Given your comments I assume you are simply looking for Array.prototype.join(';'):
let array = [
['a', 1],
['b', 2],
['c', 3]
];
let comma_value = array.join(';');
console.log(comma_value); // 'a,1;b,2;c,3'
This works due to the implicit array element ['a', 1] to string 'a,1' conversion performed within the array.join(';') method call.
If you are curious how this works: When you call array.join(';'), the individual array elements are first converted to strings via the Array.prototype.toString() method:
['a', 1].toString() // returns 'a,1'
Subsequently, those strings are joined with the ';' separator in between.
However, I don't see how this and your comments relate to the given reg() function. That code features two one-dimensional arrays with {value: ...} objects as elements.
alert( [["a",1],["b",2]].map(e=>e.join()).join(";"));
Join the inner Arrays, then the outer...
Currently I have an array using an increasing index:
var idx = 1;
var a = [];
a[idx++] = "apple";
a[idx++] = "orange";
...
console.log(a[2]);
And only accessing it by [], not using array specific functions, like length, indexOf, ...
Apparently following is also working in this case:
var a = {};
So, which one should I prefer in such case? For example any performance difference between them?
[ ] denotes an array. Arrays only hold values:
var a1 = [1, 2, 3, 4]
As #Qantas pointed out, array can hold more than just values. An array can even contain another array and/or object:
var a2 = [1, 2, ["apple", "orange"], {one: "grape", two: "banana"}];
{ } denotes an object. Objects have key-value pairs like
var a3 = {one: 1, two: 2}
In your case, it's really a matter of how you would like to be able to access the data. If you are only interested in knowing "apple", "pear", etc. Go ahead and use an array. You can access it via it's index
a1[0]; // outputs 1
a1[1]; // outputs 2
or you can iterate over it with a loop. If you use the curly braces, (given the example I gave) you could access it with
a3.one; // outputs 1
a3["two"]; // outputs 2
It's really up to you on how it would best fit your needs in this case. For a more extensive discussion see this article.
The difference is using square brackets will create an Array object while using curly brackets creates a plain object. For example:
a = [];
a[1] = 'a';
b = {};
b[1] = 'b';
a.length; // returns 2
b.length; // is undefined
a.push('z'); // add 'z' to the end of a
b.push('z'); // generates an error - undefined is not a function
// because plain objects don't have a push method
Read the MDN documentation on Array objects to know more about arrays: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
I have two arrays: ArrayA and ArrayB. I need to copy ArrayA into ArrayB (as opposed to create a reference) and I've been using .splice(0) but I noticed that it seems to removes the elements from the initial array.
In the console, when I run this code:
var ArrayA = [];
var ArrayB = [];
ArrayA.push(1);
ArrayA.push(2);
ArrayB = ArrayA.splice(0);
alert(ArrayA.length);
the alert shows 0. What am I doing wrong with .splice(0)??
Thanks for your insight.
You want to use slice() (MDN docu) and not splice() (MDN docu)!
ArrayB = ArrayA.slice(0);
slice() leaves the original array untouched and just creates a copy.
splice() on the other hand just modifies the original array by inserting or deleting elements.
splice(0) grabs all the items from 0 onwards (i.e. until the last one, i.e. all of them), removes them from the original array and returns them.
You are looking for slice:
var a = [1,2,3,4,5]
,b = a.slice();
//=> a = [1,2,3,4,5], b = [1,2,3,4,5]
you can use splice, but it will destroy your original array:
var a = [1,2,3,4,5]
,b = a.splice(0);
//=> a = [], b = [1,2,3,4,5]