Convenience method to get sub-indices of array in javascript - 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"]

Related

JavaScript arrays and understanding arr[arr.length]

What is meant by arr[arr.length]. I mean what it really means or what it really does, I cannot understand the logic of how it works. Can anybody explain?
arr.length means the length of the array that spans from index 0 to arr.length - 1.
For instance if you got arr = ["a", "b", "c"], arr.length is 3.
arr[0] is "a", arr[1] is "b" and arr[2] is "c".
arr[3] does not exist, yet. but if you do arr[arr.length] = "d", you obtain ["a", "b", "c", "d"].
This is an odd construction and usually, one should simply write arr.push("d").
const arr = ["a", "b", "c"];
console.log(arr.length, arr[0], arr[1], arr[2], arr[3]);
arr[arr.length] = "d";
console.log(arr);
arr.push("e");
console.log(arr);
This statement gets the index of the last index of the array plus one. It is used to append items to an array. Equivalent to array.push().
var fruits = ["apple", "orange", "banana", "pear"];
// appends grapes to the array
fruits[fruits.length] = "grapes";
console.log(fruits);
For further reading, check out MDN's page on array methods.
arr.length is the length of the array.
arr[arr.length] is accessing by index the array length (out of bounds as length starts at 1, not index 0).
example:
const test = [1,2,3]
test[test.length]
undefined
test[test.length-1]
3
It just requests specific index of the array, Use case: Not very elegant way of adding new element to the array, like:
arr[arr.length] = newVal
arr.push(newVal)
arr = [...arr, newVal]

VueJS pushing to an array also pushes the value to another one

Has any vuejs veteran experience this on VueJS(v2) where you have 2 arrays on a Component, and you push a value to the 1st array and the 2nd array gets the value also WITHOUT TOUCHING IT.
This is the first time I've encountered this, fyi I've been using VueJS for more than 2yrs already.
Additional information I have a VERY VERY similar component with exactly the same data variables and it doesn't happen, only on the 2nd Component.
array1 = [];
array2 = [];
array1.push('gether');
output should be
array1 = ['gether'];
array2 = [];
WHAT ACTUALLY HAPPENS
array1 = ['gether'];
array2 = ['gether'];
I've also played with the Google DevTools Vue Debugger.
Adding an entry on the array1 ONLY also adds the value on the array2.
kinda mind boggling
Because arrays in JS are reference values, so when you try to copy it using the = it will only copy the reference to the original array and not the value of the array. To create a real copy of an array, you need to copy over the value of the array under a new value variable. That way this new array does not reference to the old array address in memory.
To achieve this you can use array.slice() method as it creates a new array not a mere reference !
See Example and understand difference =>
Using reference (=)
let array = ["some text"]
// Making it equal to main array and using reference to copy
array1 = array;
array2 = array;
array1.push('gether');
console.log(array2)
Using array.slice() to clone
let array = ["some text"]
// Making it equal to main array and using slice to copy
array1 = array.slice();
array2 = array.slice();
array1.push('gether');
console.log(array2)
When you make two arrays equal to the same value, you make them equal by reference.
So
foo = ['a', 'b', 'z']
array1 = foo;
array2 = foo;
array1.push('d');
console.log(array2) //Outputs: ['a', 'b', 'c', 'd']
Is expected behaviour.
However that is not the same as the given example in your question. Run snippet below to see the difference.
To avoid this, you can use slice() to create a copy of the original array. I added an example to the code snippet.
let foo = ["a", "b"];
let array1 = foo;
let array2 = foo;
array2.push("c");
console.log(foo); // Outputs ["a", "b", "c"]
console.log(array1); // Outputs ["a", "b", "c"]
let array3 = [];
let array4 = [];
array4.push("a");
console.log(array3); // Outputs []
console.log(array4); // Outputs ["a"]
let bar = ["a", "b"];
let array5 = bar.slice();
bar.push("c");
console.log(bar); // Outputs ["a", "b", "c"]
console.log(array5); // Outputs ["a", "b"]

Merge two arrays by grouping based on elements of 1st array in Javascript

I have two arrays (arr1 & arr2) like this
var arr1 = ["A","B","C"];
var arr2 = [["A","aa"], ["A","ab"], ["A","ac"],["B","ba"],["B","bb"],["B","bc"],["C","ca"],["C","cb"]];
I want to group them together into 3rd array in javascript based on the values of first array. Desired Output:
arr3 = [ ["A",["aa","ab","ac"]], ["B",["ba","bb","bc"] ], ["C",["ca","cb"]] ]
NOTE: I had arr2 to begin with and was able to retrieve first value and remove duplicates into arr1.
Please advise.
Try like this
var arr1 = ["A", "B", "C"];
var arr2 = [
["A", "aa"],
["A", "ab"],
["A", "ac"],
["B", "ba"],
["B", "bb"],
["B", "bc"],
["C", "ca"],
["C", "cb"]
];
var newVal = arr1.map(function(x) {
var filter = arr2.filter(function(y) {
return y[0] == x;
}).map(function(y) {
return y[1];
});
return [x, filter];
})
console.log(newVal);
DEMO
NOTE: I had arr2 to begin with and was able to retrieve first value and remove duplicates into arr1.
Rather than creating arr1 as a middle step, I would probably create an object as the middle step:
var obj = arr2.reduce(function(a,b){
if (!a[b[0]]) a[b[0]] = [];
a[b[0]].push(b[1]);
return a;
},{});
// obj is now {"A":["aa","ab","ac"],"B":["ba","bb","bc"],"C":["ca","cb"]}
To convert that object to your desired output array:
var arr3 = Object.keys(obj).map(function(v) { return [v, obj[v]]; });
// [["A",["aa","ab","ac"]],["B",["ba","bb","bc"]],["C",["ca","cb"]]]
If you actually need the arr1 array for something else then:
var arr1 = Object.keys(obj);
// ["A", "B", "C"]
But notice that obj is quite useful for further processing, because if you need to get the values associated with "B" you don't need to search through an array again, you can simply say obj["B"] (which will give the array ["ba","bb","bc"]). So the second "B" value is obj["B"][1].
Further reading:
.reduce()
.map()
Object.keys()

Shorthand for creating an array of string values in 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

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