get the number of inputs given to a function js - javascript

Assume i have created a function function findInputGiven(){} and i called it somewhere below twice findInputGiven([1, 2], [3, 4]), findInputGiven([1, 2], [3, 4], [5, 6]). This function can be called with multiple inputs, i dont know how many inputs will be available in my findInputGiven function. How can i get the number of inputs given to call function.
My task is to return an array of all numbers of given arrays. If the function is called like findInputGiven([1, 2], [5, 6]), then i should return [1, 2, 5, 6].

My task is to return an array of all numbers of given arrays
What you can do is use rest parameters to get an array of all arguments and then return the flattened result. You can still get a count of the arguments if required but for this task, I don't think you'll need it.
function findInputGiven(...arrays) {
// you can get the argument count if you need it
console.log(`Got ${arrays.length} argument(s)`)
// return the flattened result
return arrays.flat()
}
console.info(findInputGiven([1, 2], [3, 4]))
console.info(findInputGiven([1, 2], [3, 4], [5, 6]))
.as-console-wrapper { max-height: 100% !important }

If you are not familiar with Rest parameters, Array.prototype.flat of ES6 feature along with don't want to "transpile" your code.
You can achieve it by using arguments.
function findInputGiven() {
const numberOfInputs = arguments.length;
console.log(`Number of inputs: ${numberOfInputs}`);
let result = [];
Object.values(arguments).forEach(function(item, index){
if(Array.isArray(item))
result = result.concat(item);
else
result.push(item);
});
return result;
}
console.log(findInputGiven([1, 2], [3, 4]))
console.log(findInputGiven([1, 2], [3, 4], [5, 6], 7))
More detailed explanation:
As you may know, rest parameters & flat() aren't supporting IE. So that is where transpiler come from :)

Related

How to use reduce method within map method to add numbers

Not sure if I am overcomplicating things but I am trying to get the sum of all the numbers inside this array of arrays:
const frames = [
[2, 0], [4, 2], [6, 0], [2, 4], [1, 5], [7, 0], [5, 2], [7, 0], [2, 6], [8, 1]
]
I am practising using map and reduce to do so:
const score = (frames) =>{
console.log(frames)
let addedScores = frames.map(frame.reduce((previousValue, currentValue) => previousValue + currentValue))
console.log(addedScores)
}
But currently getting this error:
TypeError: 2,04,26,02,41,57,05,27,02,68,1 is not a function
at Array.map (<anonymous>)
at score (/Users/x/Desktop/Programming/devacademy/bootcamp/week1/preparation/bowling-kata/game.js:8:28)
at Object.<anonymous> (/Users/x/Desktop/Programming/devacademy/bootcamp/week1/preparation/bowling-kata/game.js:17:1)
Here is a fiddle version.
Any advice and explanation would be greatly appreciated
You are almost there on this one! If you look at the stack trace for the error you are facing, you will see that an error is thrown by Array.map function, and namely that "stuff" (i.e 2,04,26,02,41,57,05,27,02,68,1) is "not a function".
The map higher-order function expects a function that it will map accross the elements of frames.
What you want is something like this:
//...
let addedScores = frames.map((frame) => frame.reduce((previousValue, currentValue) => previousValue + currentValue))
//...
Here I have only converted your addedScores expression to pass an anonymous function: (frame) => { ... } to the map function.
Hope this helps!
The resulting shape for addedScores would be: [2, 6, 6, 6, 6, 7, ...], which is the sum of each pair of numbers in frames.

How to remove an array from a nested array in JavaScript? [duplicate]

This question already has answers here:
How can I remove a specific item from an array in JavaScript?
(142 answers)
Closed 1 year ago.
Is there a way to remove an array from a nested array in JavaScript?
I have the following array:
arr = [
[1, 2],
[2, 3],
[3, 4]
]
and I want to remove the value [2, 3] from the array so that it results with:
arr = [
[1, 2],
[3, 4]
]
I have already tried the answers on How can I remove a specific item from an array?, but they don't seem to work. I was wondering if there was a fast efficient way of doing this.
Edit:
I already tried using indexOf and findIndex, and it does not return the index of an array inside of the array.
arr = [
[1, 2],
[2, 3],
[3, 4]
];
console.log(arr.indexOf([2, 3]));
console.log(arr.findIndex([2, 3]));
This did not work, even though it was suggested in the comments below.
Furthermore, using:
console.log(arr.filter(nested => nested[0] !== 2 || nested[1] !== 3));
will be inefficient as in my code I need to remove large lists, which have hundreds of values, I only provided an example in my question.
Any help would be appreciated.
var arr = [
[1, 2],
[2, 3],
[3, 4]
]
console.log('Before =>', arr);
arr.splice(1, 1); // .splice(index, 1);
console.log('After=>', arr);

Array sort and value change at the same time

I have an array below and the first number in each array means order.
What I want to do is, whenever I change the order, it resorts the array and re-index it into 2, 3, 4, 5.
const payments = [
[2, paymentName1, '5%'],
[3, paymentName2, '5%'],
[4, paymentName3, '5%'],
[5, paymentName4, '5%']
];
For example, if I change the first array order from 2 to 6, array becomes the one below.
const payments = [
[2, paymentName2, '5%'],
[3, paymentName3, '5%'],
[4, paymentName4, '5%'],
[5, paymentName1, '5%'],
];
what I currently did was to sort it and take for loop to re-order it. and I want to do it in one loop if possible. Please help me with writing this algorithm.
Thanks in advance!
Edit:
payments.sort((a, b) => a[0] - b[0]);
for (const index in payments) {
payments[index][0] = parseInt(index) + 2;
}
This is my current function. Would there be a better way to do?
thanks!
After you sort, just loop over the array and assign the new order values incrementally. There is no "better" here.
const payments = [
[2, "paymentName1", '5%'],
[3, "paymentName2", '5%'],
[4, "paymentName3", '5%'],
[5, "paymentName4", '5%']
];
function setOrder(index, newOrder) {
payments[index][0] = newOrder;
payments.sort(([a], [b]) => a - b);
for (let i = 0; i < payments.length; i++) payments[i][0] = i + 2;
}
setOrder(0, 6);
console.log(payments);
The time complexity is determined by the call to sort: O(nlogn).
Alternatively, you could use binary search to find the target index where the mutated element should go, and then rotate the array elements accordingly. Then the time complexity will be O(n). Although this has a better time complexity, the overhead of JavaScript code will make that for arrays of moderate sizes you'll get faster results with sort.

How can I get an array with a nested array whose elements have a unique order?

I have an array of arrays. How can I get an array with a nested array whose elements have a unique order?
What I have:
[[1, 2], [1, 2, 3], [3, 4]]
Expected Output:
[[1, 2, 3], [3, 4]]
I think, that I can format to JSON, and get my result with filter and indexOf ,I have tried this:
var unique = x2.map(ar=>JSON.stringify(ar).replace(/[\[\]']+/g,''))
.filter((itm, idx, arr) => arr.indexOf(itm) === idx);
Here is my try, I first sorted the array by its length then applied filter and match the index position by making use of every and includes. Here is an example:
var example = [[1, 2, 35, 7], [1, 2, 3], [35, 7], [3, 4], [4]];
var result = example.sort((a,b)=>b.length-a.length).filter((k,i,self)=>self.findIndex(p=>k.every(l=>p.includes(l)))==i);
console.log(result);
I hope this helps.

How can I really understand the method of 'Array.prototype.join'

I use the method of Array.prototype.join for multidimensional array, but I get curious result. I try to see the bottom implementation of Array.prototype.join, it show me the native code
[1,2,3,4,5,6,7,8].join('')
[1, [2], [3, [4, [5]]], [6, [7, [8]]]].join('');
I expect the output of
[1,[2],[3,[4,[5]]],[6,[7,[8]]]].join('')
to be
12345678
but the actual output is
123,4,56,7,8
.join calls .toString() on each element to turn it into a string, and Array.prototype.toString() by default concatenates all its elements with a ,.
console.log([1, 2, 3].toString());
Like others already said, toString is called upon the array. However, by providing a separator it will only join the array on which you call the method with that separator.
[
1,
[2],
[3, [4, [5]]],
[6, [7, [8]]]
].join("")
Will simply join the first level elements together, calling toString on elements that aren't a string.
1.toString() + "" +
[2].toString() + "" +
[3, [4, [5]]].toString() + "" +
[6, [7, [8]]].toString()
Where the "" is the separator. Resulting in 123,4,56,7,8 where 3,4,5 is the first nested array and 6,7,8 the second (with more than 1 element). If you'd like to join the elements recursive you could create your own method.
Array.prototype.deepJoin = function (separator) {
return this
.map(e => Array.isArray(e) ? e.deepJoin(separator) : e)
.join(separator);
};
var array = [1, [2], [3, [4, [5]]], [6, [7, [8]]]];
console.log(array.join());
console.log(array.deepJoin());
console.log(array.join(""));
console.log(array.deepJoin(""));
console.log(array.join(" - "));
console.log(array.deepJoin(" - "));
The join method also invoke toString() on each element.
You have
[2].toString() -> 2
[3, [4, 5]].toString() -> 3,4,5
And so on. The toString method on an array never preserves square parenthesis

Categories