Function that creates an array [duplicate] - javascript

This question already has answers here:
How to create an array containing 1...N
(77 answers)
Fastest way to fill an array with multiple value in JS. Can I pass a some pattern or function to method fill insted of a single value in JS? [duplicate]
(1 answer)
Closed 4 years ago.
I want to create a function that takes input from user and returns an array with all the numbers from 1 to the passed number as an argument. Example: createArray(10) should return [1,2,3,4,5,6,7,8,9,10]. I came up with this solution:
function createArray(input) {
var value = 0;
var array = [];
for (i=0;i<input;i++) {
value++;
array.push(value)
console.log(array)
}
}
createArray(12);
What is the correct and better way of doing it?

I would prefer to use Array.from:
const createArray = length => Array.from(
{ length },
// Mapper function: i is the current index in the length being iterated over:
(_, i) => i + 1
)
console.log(JSON.stringify(createArray(10)));
console.log(JSON.stringify(createArray(5)));

There is no need for the extra variable just do this:
function createArray(input) {
var array = [];
for (i = 0; i <= input; i++) {
array.push(i);
}
return array;
}

Related

Fastest and Most Efficient way to check for duplicates in a javascript array [duplicate]

This question already has answers here:
Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array
(97 answers)
In Javascript, how do I check if an array has duplicate values?
(9 answers)
Checking for duplicate strings in JavaScript array
(13 answers)
Closed 5 months ago.
I am writing a javascript function that takes a nested array and returns the numbers that occurs more than once in that array.
I believe my function is accurate (meaning that it passes their "Correctness test" ) but i am after efficiency, how efficient is this code?
For example - Lets call the name of the function deepSort(nestedArray) where nestedArray is the nested array parameter
function deepSort(nestedArray) {
const flatArr = nestedArray.flat().sort();
let results = []
for (let i = 0; i < flatArr.length - 1; i++) {
if (flatArr[i + 1] == flatArr[i]) {
results.push(flatArr[i]);
}
}
return (results.filter((item, index) => results.indexOf(item) === index)).join()
}
const a = deepSort([[1,3,4,5], [4,7,9,1,3], [2,3,5], [1,2,3,4]]) // Returns 1,2,3,4,5
console.log(a);
const b = deepSort([[1,2,3], [4,5], [6,7,8], [2,9,0]]) // Returns 2
console.log(b);
const c = deepSort([[2,7,9], [4,3], [9,6,5], [1,4,3]]) // Returns 3,4,9
console.log(c);
Can this code be optimized any more for speed and efficiency when handling extremely large values of data?

Where are the callback parameters coming from in a recreation of a .map prototype function? [duplicate]

This question already has answers here:
Why does Javascript's array map callback require extra arguments
(3 answers)
How are array methods aware of the values they are called on?
(3 answers)
'thisArg' parameter in Array.prototype.map
(1 answer)
Javascript array.prototype.map when/why use third argument [duplicate]
(3 answers)
Closed 7 months ago.
I'm recreating Javascript's map function and i'm not understanding where these parameters are coming from:
(this[index], index, this)
I understand what this is the array, i understand this[index] is the value, and index is the number that keeps track of the index on iteration, but where is that all coming from when i'm only passing in:
x => x * 5
that's the part i'm confused about and havne't found a good explanation about it online.
Array.prototype.mymap = function(callback) {
const resultArray = [];
for (let index = 0; index < this.length; index++) {
resultArray.push(callback(this[index], index, this)); // confused about these parameters
}
return resultArray;
}
const sample = [1,2,3];
var output = sample.mymap(x => x * 5);
console.log(output);

Removing duplicates of an array [duplicate]

This question already has answers here:
Get all unique values in a JavaScript array (remove duplicates)
(91 answers)
Closed 12 months ago.
How can i check if an array has element twice and log only the element that is not.
const duplicateElements = (array) => {
for(let numbers of array) {
// code here
}
}
const numbers = [1,3,2,4,1,3,2];
duplicateElements(numbers);
// Output 4
With the JS function filter you can archive this. First you have to iterate your array. then check with the filter function how many times the current value is inside your array. If equal 1 then push to an result array.
const d = [];
const arr = [1,3,2,4,1,3,2]
arr.forEach((e) => {
if (arr.filter(x => x == e).length === 1) {
d.push(e);
}
})
console.log(d);

Create an object from a string using javascript [duplicate]

This question already has answers here:
split string in two on given index and return both parts
(10 answers)
Closed 6 years ago.
I have a string that looks like this:
YA...Y..............
I need to create an object out of this. I was going to try to create an array from the string (but can't see how) if there was a way of doing a split on character index.
Then I was going to loop through that array and create an object.
I had a solution a bit like this:
// Creat an array
var array = [];
// Get our string length
var len = profileString.length - 1;
// Loop through our lengths
for (var i = 0; i < length; i++) {
// Get our current character
var char = profileString[i];
// Push our character into our array
array.push(char);
}
// Create our object
var obj = {};
// Loop through our array
array.forEach(function (item, index) {
// Add our item to our object
obj['item' + index] = item;
});
// Return our object
return obj;
I need to know if there is a better way of doing this.
You could use Object.create.
console.log(Object.create([...'YA...Y..............']));
ES5
console.log(Object.create('YA...Y..............'.split('')));

Sort Javascript Object [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Sorting JavaScript Object by property value
Sort JavaScript object by key
I've written a function called frequency() that takes an Array, counts the number of times a string is found within it, and then returns an object based on these results.
Code:
var array = ["Diesel","Asos","Diesel","Paul Smith"];
function frequency(array) {
var frequency = {}, value;
for(var i = 0; i < array.length; i++) {
value = array[i];
if(value in frequency)
frequency[value]++;
else
frequency[value] = 1;
}
return frequency;
}
ordered = frequency(array);
Sample output:
{"Asos":1,"Diesel":2,"Paul Smith":1}
How can I now sort this outputted object based on the counted frequency value?

Categories