This question already has answers here:
Splitting a JS array into N arrays
(23 answers)
Closed 8 years ago.
How do I slice an array like this:
var a = [1, 2, 3, 4, 5, 6 , 7, 8];
into thirds (ie. three arrays, like this):
[1, 2, 3]
[4, 5, 6]
[7, 8]
Here's what I've got so far:
var first = a.slice(0, Math.ceil(a.length / 3));
var seconds = ???
var third = ???
This works, though it can be cleaned up:
var m, n;
var first, second, third;
m = Math.ceil(a.length / 3);
n = Math.ceil(2 * a.length / 3);
first = a.slice(0, m);
second = a.slice(m, n);
third = a.slice(n, a.length);
First, get the length. Nice and simple: a.length
Next, divide by three and round up. This will be the size of your pieces.
Finally, use a.slice() with appropriate arguments to get the resulting arrays.
Write some code using the above algorithm, and let us know if you have any more specific problems :)
Related
This question already has answers here:
Sort two arrays the same way
(12 answers)
Closed 18 days ago.
I need to change indexes of elements in arr a due to their indexes in arr b.
const a = [4,3,2,1,5];
const b = [1,2,3,4,5];
console.log(a) [1,2,3,4,5]
If you mean ordering array a according to array b, then you can do like this:
a.forEach((element,i) => {
// first get the index of a[i] from array b
const index = b.indexOf(a[i])
// then swap them
const temp = a[index];
a[index] = a[i];
a[i] = temp;
})
You could sort by using the other array as index. If this daoes not work with real data, please andd a small amount of data to highlight the problem.
const
a = [4, 3, 2, 1, 5],
b = [1, 2, 3, 4, 5];
a.sort((l, r) => b[l - 1] - b[r - 1]);
console.log(...a);
I'm trying to solve this question on LeetCode:
Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
Note: The number of elements initialized in nums1 and nums2 are m and n respectively.
You may assume that nums1 has enough space (size that is equal to m + n) to hold additional elements from nums2.
I ended up with coming up with this code:
var merge = function(nums1, m, nums2, n) {
var nums = [];
nums1.length = m;
nums2.length = n;
nums = nums.concat(nums1);
console.log(nums);
nums = nums.concat(nums2);
console.log(nums);
nums = nums.sort();
console.log(nums);
return nums;
}
This is what the 'run code' says:
Your input
[1,2,3,0,0,0]
3
[2,5,6]
3
stdout
[ 1, 2, 3 ]
[ 1, 2, 3, 2, 5, 6 ]
[ 1, 2, 2, 3, 5, 6 ]
Output:
[1,2,3]
Expected
[1,2,2,3,5,6]
(an image version if the quotes weren't clear)
When I'm console.logging the array, the answer is correct but for some reason returning the array gives a completely different output
Can anyone help in this?
I think the hint here is that nums1 is big enough to hold n+m values. So the way to solve this problem is to work backwards through both arrays, filling the empty space in nums1 as you go. So for example, for the first iteration of the loop, you would compare nums1[n-1] and nums2[m-1] and put whichever is larger into nums1[n+m-1]. You then continue this for as long as you have values in either array, copying exclusively from the other if one runs out:
const merge = function(nums1, m, nums2, n) {
n--; m--;
for (let i = m + n + 1; i >= 0; i--) {
nums1[i] = (m < 0 || n >= 0 && nums2[n] > nums1[m]) ? nums2[n--] : nums1[m--];
}
return nums1;
}
console.log(merge([1, 2, 3, 0, 0, 0], 3, [2, 5, 6], 3));
This code is O(n) (as compared to your sort which is O(nlogn)) and requires no additional space.
This question already has answers here:
Split array into chunks
(73 answers)
Closed 3 years ago.
How can I split an array into equal sized arrays:
var a = [1,2,3,4,5,6,7,8];
var b = a.split(2);
// b is equal to [[1,2],[3,4],[5,6],[7,8]];
// one possible way might be something like
[0,1,2,3].map(_ => a.slice(_* 2, _+2));
const chunk = (arr, size) => arr.reduce((carry, _, index, orig) => !(index % size) ? carry.concat([orig.slice(index,index+size)]) : carry, []);
console.log(chunk([1,2,3,4,5,6,7,8], 2))
For the second index for splicing, you need to add one and multiply with the length of the inner arrays.
var a = [1, 2, 3, 4, 5, 6, 7, 8],
b = [0, 1, 2, 3].map(i => a.slice(i * 2, (i + 1) * 2));
console.log(b);
This question already has answers here:
Javascript: take every nth Element of Array
(6 answers)
Closed 6 years ago.
I have an array, and want to return only every third element as a new array (starting at 0).
For example:
let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];
let newArr = [1, 4, 7];
This is the way I am currently doing this:
let newArr = [];
for(let x = 0; x < arr.length; x += 3) {
newArr.push(arr[x]);
}
return newArr;
Is there a way to do this with arr.map? Is there just an easier way to do this?
You can alternatively do it with a filter,
let newArr = arr.filter((_,i) => i % 3 == 0);
But remember, using basic for loop is bit more efficient than others in some contexts.
This question already has answers here:
Why does parseInt yield NaN with Array#map?
(8 answers)
Closed 6 years ago.
Trying to run a simple javascript to parse single digit ints in a string as follows:
var s = "22123222222213123212322123213222";
var a = s.split("");
var b = a.map(parseInt);
console.log(b);
[2, NaN, 1, 2, 3, 2, 2, 2, 2, 2, 2, 2, 1, 3, 1, 2, 3, 2, 1, 2, 3, 2, 2, 1, 2, 3, 2, 1, 3, 2, 2, 2]
Why is there a NaN for element with index 1?
Fiddle in the console here:
https://jsfiddle.net/po6oy1ws/
EDIT
After getting the correct answer below I felt I had to lookup this "map(Number)" business. Turns out Mozilla has a "gotcha" clause concerning this specific case. Mozilla gotcha case
The parseInt has two parameters
parseInt(string, radix);
And map's callback accepts three parameters:
map(currentValue, index, array)
Therefore the index of the currentValue was passed as a radix to the parseInt function. Use parseInt with radix explicitly:
var s = "22123222222213123212322123213222";
var a = s.split("");
var b = a.map(e => parseInt(e, 10));
Or use Number instead of parseInt:
var s = "22123222222213123212322123213222";
var a = s.split("");
var b = a.map(Number);