Rearrange array in Javascript with ES6 - javascript

I want to reorder an Array with ES6.
For example:
[1,2,3,4,5,6,7,8,9]
When my starting number is 5, I want a new array like this:
[5,6,7,8,9,1,2,3,4].
I am able to fix this by looping, comparing, slicing, glueing the thing back together.
However I've read some interesting array functionality with ES6 that might make this easier. But I'm having trouble putting this into practise.

It can be
let newArr = [...arr.slice(arr.indexOf(5)), ...arr.slice(0, arr.indexOf(5))]
or
let newArr = [...arr];
newArr = [...newArr.splice(arr.indexOf(5)), ...newArr];

So I am not sure this is what you have in mind, but assuming you mean we are starting at 5 because its value (not position if you start counting at 1) is 5, the following should work (though maybe not the newfangled idea you wanted).
var startArr =[1,2,3,4,5,6,7,8,9];
var startIndex=startArr.indexOf(5);//finds 5, if you meant just because it is the 5th. say startArr=5-1
if (startIndex!=-1){
var a1=startArr.slice(startIndex);
var a3=a1.concat(startArr.slice(0,startIndex));
//a3 now contains what you wished for, you may console.log(a3) to see
}

Related

How to chain two splice methods in Javascript?

In the following example, splice().splice() didn't work. What am I missing? How can I chain two splice methods in a single line? Thank you for any advice!
function test() {
var data = [0,1,2,3,4,5];
data.splice(0,2).splice(-1); // Removed only the first two elements, but not the last element.
console.log(data) // Returned [ 2, 3, 4, 5 ]
var data = [0,1,2,3,4,5];
data.splice(0,2); // Removed the first two elements.
data.splice(-1); // Removed the last element.
console.log(data) // Returned [ 2, 3, 4 ]
}
splice returns the removed elements, so chaining them in a single statement won't really work - you don't want to operate on the removed elements, you want to operate on the original array both times.
Usually, in this sort of situation, the right approach is to use slice instead, which is both easier to work with (just specify a start (inclusive) and end (exclusive) index) and is more functional (you get a new array instead of mutating an existing one - it's nice to avoid mutation when possible, makes code more understandable).
const data = [0,1,2,3,4,5];
console.log(data.slice(2,5));
You can do this, although I don't recommend this because it makes the code confusing
const data = [0,1,2,3,4,5];
console.log(data.splice(2,4).splice(0,3)); // Returned [2,3,4]

What is the best way to "Cut & Paste" the contents of one array into another array in JavaScript?

I've been using all of these methods to accomplish this, but I don't know which one is best practice from a professional standpoint. Am I missing a very obvious way to do this? One that everybody ...except me... uses on a daily basis?
EDIT: arr1 has to be empty at the end of the operation.
let arr1 = [9,10,11,12];
let arr2 = [2,3,4,5];
arr2 = arr2.concat(arr1.splice(0,arr1.length));
arr2.push(...arr1);
arr1 = [];
arr2 = [...arr2,...arr1];
arr1.length = 0;
for (let i = 0; i < 4; i++) {
arr2.push(arr1.shift());
}
arr2 = arr2.concat(arr1);
arr1 = [];
console.log("arr1", arr1)
console.log("arr2", arr2)
console.log(arr2.length)
From what I understand you need to mutate the two arrays so you could use Array.prototype.push() and Array.prototype.splice() like this (you don't need to provide the second parameter of Array.prototype.splice()):
const arr1 = [9, 10, 11, 12];
const arr2 = [2, 3, 4, 5];
arr2.push(...arr1.splice(0));
console.log(arr1, arr2);
There are many ways to do that as you have stated. It is like a variation on a theme in musical composition. All the variations you have shown is correct to my eyes. First one and last one are clever in a way too. But there comes a pay off with those cleverness. I would direct you to concepts like desructive and non-desructive procedures, or functions if you want to call them so. I know a lot of entries will tell you about changing the object or creating a new one, to me it is clearer and more basic to refer to them as I have denoted.
Some functions are defined to be non-desructive, and others are not. I would suggest the way to go with non-destrcutive approach. Although the non-desructive operations in an interpreted language like JavaScript hints the inherent resource hungriness and themselves must be mitigation for resource wasting, their use might not worth it provided the class of bugs they might introduce if not somethings kept in mind. unless huge amounts of data is moved around and the resources is not enough for non-d approach I would not use destructive functions.
Everyday use, I always use non-destructive procedures. I almost never need desructive methods like splice, push, pop, shift, unshift. Non-desructive methods like concat, slice are enough for not only me for almost every need.
For specific example above I would code like:
arr2 = arr2.concat(arr1); // or arr2 = [...arr2, ...arr1];
arr1 = []; // or arr1 = arr1.slice(arr1.length) but that seems a waste since you really want to empty the arr1.
In addition it would be better if you completely code in a way there is no need to those self assignations anyways. It is possible. If you just return from functions, and pass them arguments whenever you need anything from outside of the functions.

Javascript - List (array) length and getting an item from the list not working

I'm practicing JavaScript (just started this week) on vscode with the Quokka.js extension. Right now I'm initializing a list called "things" and trying to get the length of the list and getting some items out of it. This is my code:
var things = ['bananas', 'apples', 7];
things.length;
things[0];
The last two rows return nothing to me, not even "undefined".
How do I get vscode to return the length and the first object from the list using [0]? If it is not possible in vscode, what program should I use for learning JavaScript?
I also tried initializing the list as an array with
Array things = ['bananas', 'apples', 7];
but this does not seem to be allowed.
Moreover, for example the command
things.splice
seems to work in vscode.
Even if you're using Quokka, it's better to output using console.log. Quokka works very well with console.log.
Also try not to use var or declare array using Array. This is JavaScript, not Java.
// Do not use var
let things = ['bananas', 'apples', 7];
console.log(things.length);
console.log(things[0]);
// This will not work
// This does not make any sense either
Array things = ['bananas', 'apples', 7];
JavaScript Array is not Class or an interface by using which you can declare it's instances. JavaScript Array is a global object. There are no classes in JavaScript.

Array.prototype.map() and Array.prototype.forEach()

I've an array (example array below) -
a = [{"name":"age","value":31},
{"name":"height (inches)","value":62},
{"name":"location","value":"Boston, MA"},
{"name":"gender","value":"male"}];
I want to iterate through this array of objects and produce a new Object (not specifically reduce).
I've these two approaches -
a = [{"name":"age","value":31},
{"name":"height (inches)","value":62},
{"name":"location","value":"Boston, MA"},
{"name":"gender","value":"male"}];
// using Array.prototype.map()
b = a.map(function(item){
var res = {};
res[item.name] = item.value;
return res;
});
console.log(JSON.stringify(b));
var newObj = [];
// using Array.prototype.forEach()
a.forEach(function(d){
var obj = {};
obj[d.name] = d.value;
newObj.push(obj)
});
console.log(JSON.stringify(newObj))
Is it not right to just use either one for this sort of operations?
Also, I'd like to understand the use case scenarios where one will be preferred over the other? Or should I just stick to for-loop?
As you've already discussed in the comments, there's no outright wrong answer here. Aside from some rather fine points of performance, this is a style question. The problem you are solving can be solved with a for loop, .forEach(), .reduce(), or .map().
I list them in that order deliberately, because each one of them could be re-implemented using anything earlier in the list. You can use .reduce() to duplicate .map(), for instance, but not the reverse.
In your particular case, unless micro-optimizations are vital to your domain, I'd make the decision on the basis of readability and code-maintenance. On that basis, .map() does specifically and precisely what you're after; someone reading your code will see it and know you're consuming an array to produce another array. You could accomplish that with .forEach() or .reduce(), but because those are capable of being used for more things, someone has to take that extra moment to understand what you ARE using them for. .map() is the call that's most expressive of your intent.
(Yes, that means in essence prioritizing efficiency-of-understanding over efficiency-of-execution. If the code isn't part of a performance bottleneck in a high-demand application, I think that's appropriate.)
You asked about scenarios where another might be preferred. In this case, .map() works because you're outputting an array, and your output array has the same length as your input array. (Again; that's what .map() does). If you wanted to output an array, but you might need to produce two (or zero) elements of output for a single element of input, .map() would be out and I'd probably use .reduce(). (Chaining .filter().map() would also be a possibility for the 'skip some input elements' case, and would be pretty legible)
If you wanted to split the contents of the input array into multiple output arrays, you could do that with .reduce() (by encapsulating all of them as properties of a single object), but .forEach() or the for loop would look more natural to me.
First, either of those will work and with your example there's no reason not to use which ever is more comfortable for your development cycle. I would probably use map since that is what is for; to create "a new array with the results of calling a provided function on every element in this array."
However, are you asking which is the absolute fastest? Then neither of those; the fastest by 2.5-3x will be a simple for-loop (see http://jsperf.com/loop-vs-map-vs-foreach for a simple comparison):
var newObj = [];
for (var i = 0, item; item = a[i]; i++) {
var obj = {};
obj[item.name] = item.value;
newObj.push(obj);
});
console.log(JSON.stringify(newObj));

Finding the min first value of a list of pairs of numbers in JavaScript

I have a list of "tuples" in javascript, something like [[1,2], [2,4], [3,5], [5,2], ..., [x, y]] and I would like to find the minimum of the first values in such a way that I can get both values of the "tuple". So in this case I would get the value [1,2]. This seems like something that could be done with the apply function, but I am somewhat new to some of the finer points in JavaScript like the apply function. Could anyone help me out with getting started with doing this? Thanks!
As Sirko said, you can do that with a simple for loop, comparing each first value with its previous value. You can also do that with the reduce1 array method, to achieve shorter code:
var tuples = [[1,2], [2,4], [3,5], [5,2]];
var tupleWithMinFirstValue = tuples.reduce(function(previous, current){
return current[0] < previous[0] ? current : previous;
}, [Infinity]);
console.log(tupleWithMinFirstValue);
http://jsfiddle.net/wAGMX/
1 The link also provides compatibility info, and a polyfill.

Categories

Resources