Javascript: how to use the push method? - javascript

I have a problem which I try to solve and I am struggling.
Can someone please explain me how the code below works, I read about different array methods but still cannot solve the problem below. Thanks.
it('should add elements at the end of the array with the push method', function () {
var nums = [1,2,3];
// every array has a method called 'push'
// It is a function that accepts as its first argument a value
// The passed value gets added to the array at the end (last position)
nums.push(4);
expect(nums).toEqual();
expect(nums.length).toEqual();
// Note that we don't save what push returns, we just call it.
// Push has the side effect of adding a value to the array, but it doesn't return the new array
// What do you think it returns?
var pushResult = nums.push();
expect(nums.length).toEqual();
expect(pushResult).toEqual();
var pushResult = nums.push('hello');
expect(nums.length).toEqual();
expect(pushResult).toEqual();
});

This code is a part of a unit test.
You need to make change in the code to pass assertions.
Exemple:
var nums = [1,2,3];
nums.push(4);
expect(nums).toEqual([1,2,3,4]); // true

The push() method adds new items to the end of an array, and returns the new length.
W3Schools Documentation
Mozilla Documentation

var arr = [
"ehy",
"you",
"Ciao"
];
console.log(arr.push("riciao"));
console.log(arr);

push() adds a new item/items to the end of an array.
Example
var numbers = [1, 2, 3, 4];
numbers.push(5);
The result of numbers will be:
[1, 2, 3, 4, 5]

var array=[1,2,3,4,5];
array.push(6);
array.push(7,8);
8
array
(8) [1, 2, 3, 4, 5, 6, 7, 8]
array.push({name:'Hello',operation:'push me as an object'});
9
array
(9) [1, 2, 3, 4, 5, 6, 7, 8, {…}]0: 11: 22: 33: 44: 55: 66: 77: 88: {name: "Hello", operation: "push me as an object"}length: 9__proto__: Array(0)

Related

how does this concat command work with this array?

I came across this JS problem but I can't figure out the syntax of how it's working, could someone please help to explain? I don't understand the empty square bracket syntax at the start and then how the concat is being applied with another empty square bracket? it's just quite confusing for me.
Appreciate any help to step through this.
let arr = [[1, 2],[3, 4],[5, 6, 7, 8, 9],[10, 11, 12]];
let flattened = [].concat.apply([], arr);
// [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]
let arr = [[1, 2],[3, 4],[5, 6, 7, 8, 9],[10, 11, 12]];
let flattened = [].concat.apply([], arr);
*first array*---| |---*second array*
The first array has one goal:
to invoke concat() method with this. Here this is the second array. Then the first array is thrown away
Then apply() method flattens the arr array to one level.
You can check it:
let foo = [0].concat([1,2,3], [[1,2,3]] );
console.log(foo)
UPDATE:
In addition, the first array can be removed:
const arr = [[1, 2],[3, 4],[5, 6, 7, 8, 9],[10, 11, 12]];
const flattened = Array.prototype.concat.apply([], arr);
console.log(flattened)
Some info how apply() works.
In addition, it would be really useful to know how apply() flattens array items to one level or how apply() takes an array of arguments and treats each element of that array as a single argument.
Let me show a simple example. We have the following object and method:
const showFullName = (arg_1, arg_2) => {
console.log(`arg_1 is ${arg_1}`);
console.log(`arg_2 is ${arg_2}`);
}
let foo = {};
showFullName.apply(foo, ['firstName', 'surname']);
The [] is an empty array. The concat function concatenate two or more arrays: [].concat(arr[0], arr[1], arr[2], arr[3])
The catch here is to know how apply works. The second parameter of apply is an array of parameters. It's like doing this (if you're familiar with the concept of desctructuring):
[].concat(...arr)
You can read more about apply here

JS - For Loops Pushing Array

I have an initial array,
I've been trying to change values (orders) by using pop, splice methods inside a for loop and finally I push this array to the container array.
However every time initial array is values are pushed. When I wrote console.log(initial) before push method, I can see initial array has been changed but it is not pushed to the container.
I also tried to slow down the process by using settimeout for push method but this didnt work. It is not slowing down. I guess this code is invoked immediately
I would like to learn what is going on here ? Why I have this kind of problem and what is the solution to get rid of that.
function trial(){
let schedulePattern = [];
let initial = [1,3,4,2];
for(let i = 0; i < 3; i++){
let temp = initial.pop();
initial.splice(1,0,temp);
console.log(initial);
schedulePattern.push(initial);
}
return schedulePattern;
}
**Console.log**
(4) [1, 2, 3, 4]
(4) [1, 4, 2, 3]
(4) [1, 3, 4, 2]
(3) [Array(4), Array(4), Array(4)]
0 : (4) [1, 3, 4, 2]
1 : (4) [1, 3, 4, 2]
2 : (4) [1, 3, 4, 2]
length : 3
When you push initial into schedulePattern, it's going to be a bunch of references to the same Array object. You can push a copy of the array instead if you want to preserve its current contents:
schedulePattern.push(initial.slice(0));
Good answer on reference types versus value types here: https://stackoverflow.com/a/13266769/119549
When you push the array to schedulepattern, you are passing a reference to it.
you have to "clone" the array.
use the slice function.
function trial(){
let schedulePattern = [];
let initial = [1,3,4,2];
for(let i = 0; i < 3; i++){
let temp = initial.pop();
initial.splice(1,0,temp);
console.log(initial);
schedulePattern.push(initial.slice());
}
return schedulePattern;
}
​
You have to know that arrays are mutable objects. What does it mean? It means what is happening to you, you are copying the reference of the object and modifying it.
const array = [1,2,3]
const copy = array;
copy.push(4);
console.log(array); // [1, 2, 3, 4]
console.log(copy); // [1, 2, 3, 4]
There are a lot of methods in Javascript which provide you the way you are looking for. In other words, create a new array copy to work properly without modify the root.
const array = [1,2,3]
const copy = Array.from(array);
copy.push(4);
console.log(array); // [1, 2, 3]
console.log(copy); // [1, 2, 3, 4]
I encourage you to take a look at Array methods to increase your knowledge to take the best decision about using the different options you have.

what does max() function do in javascript if array has several equally large numbers

If we get something like
array=[5,5,5,5,3,2];
return Math.max.Apply(Math,array);
How do I get it to return the numbers from first to last if such a case occurs.
To answer the question in the title:
what does max() function do in javascript if array has several equally
large numbers
The answer is, nothing. Math.max() doesn't act on arrays.
You can pass an array by spreading the items as arguments to max():
Math.max(...[1,2,3]) // 3
Or as you've seen, with apply():
Math.max.apply(Math, [1,2,3]) // 3
If the question is more:
What does Math.max() do when more than one of the same maximum number is given?
The answer is, it returns that number:
const a = [5, 5, 5, 5, 3, 2]
const max = Math.max(...a)
console.log(max) // 5
This question is confusing:
How do I get it to return the numbers from first to last if such a case occurs.
You want it to return a sorted array? From [5, 5, 5, 5, 3, 2] to [2, 3, 5, 5, 5, 5]?
a.sort() // [2, 3, 5, 5, 5, 5]
You want dupes removed? From [5, 5, 5, 5, 3, 2] to [2, 3, 5]?
Array.from(new Set(a)) // [2, 3, 5]
Could you clarify your question?
The best way to do this is the following:
var a = [5,5,5,5,3,2];
var largest = Math.max.apply(null,a)
var filtered = a.filter(function(item) {
item === largest
});
Where filtered will have contain all the largest elements.
In #Clarkie's example, he's calling Math.max more frequently than needed.
In both Dan and Clarkie's example they're capitalizing Apply which is incorrect, the correct function to call is Math.max.apply and Math need not be passed in as the first argument.
See the following for a working example:
https://jsfiddle.net/fx5ut2mm/
Modifying #Clarkie's very nice idea. We can boil it down to...
var a = [5,5,5,5,3,2],
m = Math.max(...a),
f = a.filter(e => e == m);
document.write("<pre>" + JSON.stringify(f) + "</pre>");

Finding the lowest number in an array using split('') and reverse();

I am trying to find the min value of an array, and am trying to do it by sorting the array, and then reversing the array, and then calling the very first index of the array.
Unfortunately with what I have been trying, I keep getting 9. (don't know why) Can anybody take a quick look at what I have been doing and bail me out here? (i'm using js)
var minny = [4, 3, 5, 2, 6, 3, 4, 5, 2, 3, 4, 6, 7, 8, 9, 9, 1, 11, 25];
var smallest = function (minny){
minny = minny.sort('');
var sorted = minny + " ";
sorted = minny.reverse('').join('');
return sorted[0];
}
console.log(smallest(minny))
By default the sort method sorts elements alphabetically(11 comes before 9) and therefore you need to add a compare function as a param.
var smallest = function (minny) {
minny = minny.sort(function(a, b) { return a - b; });
return minny[0];
}
console.log(smallest(minny))
JSFIDDLE.
Based on your code, you could just do
return minny.sort()[0];
So, your full code example becomes
var minny = [4, 3, 5, 2, 6, 3, 4, 5, 2, 3, 4, 6, 7, 8, 9, 9, 1, 11, 25];
var smallest = function (minny){
return minny.sort()[0];
}
console.log(smallest(minny))
You're calling minny.sort('') which is using the default natural sort, so 11 and 25 end up near the beginning because of the 1 and 2.
What you have to do is call sort with a function that compares numbers, such as:
minny.sort(function(a,b) { return b-a; });
This will sort minny the way you want it.
There is no need to even call reverse and join afterwards, just return the first item. "return sorted[0]" is fine but will fail if there are no items, so you might just want to call "return sorted.shift()" instead. This will return the first item too, but won't fail if the array is empty.
PS. your call to minny.reverse also has an empty string as a parameter. That's not needed, reverse takes no parameters.
sort() sorts alphabetically by string representation, so in your case it would result in 1, 11, 2, 2, 25, .... You have to provide a comparison function for correct integer sorting, although in your specific case it doesn't really make a difference.
var smallest = function (minny){
minny = minny.sort(function(a, b){return a-b});
return minny[0];
}
See jsfiddle
Using sort is fairly short code to write, and it will return the correct number if you use minny.sort(function(a,b){return a-b})[0].
If you have a large unordered array you are running the comparison many times and you are sorting the array, which is not usually what you want to do to an array.
It may be better to just iterate the members and compare each just once to the lowest fond so far.
var minny= [4, 3, 5, 2, 6, 3, 4, 5, 2, 3, 4, 6, 7, 8, 9, 9, 1, 11, 25];
var smallest= function(minny){
var min= Infinity;
minny.forEach(function(next){
if(next<min) min= next;
});
return min;
}
Or use Math.min, if this is code golf:
Math.min.apply(Array,minny);

Array.prototype.unshift.call(arguments,....) how can it be done?

i am trying to implement different array methods on arguments only for experiment purpose.I was able to use slice and join methods.But i can't figure out how can i add an extra element in arguments list using unshift method.it is giving an unexpected result .it is giving the value 3 ,which i don't know from where it is comming.how it can be done?
<html>
<body>
<script>
function init(){
console.log(arguments);
console.log(arguments.length);
console.log(Array.prototype.join.call(arguments,'__'));
console.log(Array.prototype.unshift.call(arguments));
}
init(1,2,3);
</script>
</body>
</html>
result:
Arguments { 0: 1, 1: 2, 2: 3, 2 more… }
3
"1__2__3"
3
From MDN:
Returns
The new length property of the object upon which the method was called.
It's returning 3 because arguments.length is 3 when you call it and you're not passing any new elements to the method.
You should be able to just call:
console.log(Array.prototype.unshift.call(arguments, "a", "b", "c")));
console.log(arguments);
And see:
6
Arguments { 0: "a", 1: "b", 2: "c", 3: 1, 4: 2, 5: 3, 2 more… }
That's because unshift returns the number of elements in the modified array, but modifies the array in-place:
array = [1,2,3]
// [1, 2, 3]
array.unshift(7)
// 4
array
// [7, 1, 2, 3]

Categories

Resources