Related
function fMI(num,arr){
let digit = arr.toString().split('');
let realDigit = digit.map(Number);
console.log("Is RealDigit an array: ",Array.isArray(realDigit));
console.log(realDigit.filter((v,i,a) => (v==num)? i:''));
}
fMI(1,[1, 11, 34, 52, 61]);
// Create a function that takes a number and an array of numbers as a parameter // and returns the indices of the numbers of the array which contain the given number // or returns an empty list (if the number is not part of any of the numbers in the array)
Sample output:
// console.log(findMatchingIndexes(1, [1, 11, 34, 52, 61]));
// should print: [0, 1, 4]
I am struggling to return the indexes of the values from an array.
The code I have written so far takes one number and compares it to the array which the function takes in.
Now, I am at the phase where I want to to return the indexes where the array values equal to the number taken by the function for comparison.
How can I make this work, cause after the filter method, I get only 3 times the number 1, which is not right.
function fMI(num:number,arr:number[]){
let digit = arr.toString().split('');
let realDigit = digit.map(Number);
console.log("Is RealDigit an array: ",Array.isArray(realDigit));
console.log(realDigit.filter((v,i,a) => (v==num)? i:''));
}
fMI(1,[1, 11, 34, 52, 61]);
New answer
You can use the string method includes like so:
function fMI(num: number, arr: number[]) {
const indexes: number[] = [];
arr.forEach((value, index) => {
if (value.toString().includes(num.toString())) {
indexes.push(index);
}
})
return indexes;
}
fMI(1, [1, 11, 34, 52, 61]); // [0, 1, 4]
Old answer
You can use forEach with a second argument that is the element index. Note that you are specifying arr as an array of number, so there's no need to convert them to numbers again.
function fMI(num: number, arr: number[]) {
const indexes: number[] = [];
arr.forEach((value, index) => {
if (value === num) {
indexes.push(index);
}
})
return indexes;
}
The 4 lines you have written doesn't help with the logic, that's why I removed it. If you want to know why, leave a comment on this answer and I will reply your questions.
You can use a traditional for loop:
function fMI(num, arr) {
let result = [];
let numArr = arr.map(item => Number(item));
for (var i = 0; i < numArr.length; i++) {
if (numArr[i] == num) {
result.push(i);
}
}
console.log(result);
}
fMI(1, [1, 11, 34, 52, 61]);
Here's an interesting take:
function fMI(num,arr) {
return arr
.map((n) => n.toString().split('')
.map((m) => parseInt(m)))
.map((o, i) => o.some((p) => p === num) ? i : null)
.filter((f) => f !== null);
}
const result = fMI(1,[1, 11, 34, 52, 61]);
console.log(result);
First we go through all the numbers in the array, convert them to strings and split them to replace the original numbers with arrays of digits. Then we run those digit arrays through parseInt it convert them to number arrays. Finally we use .some to check if any of the digits in the digit array is num and return an array of indexes or nulls which we run through a filter that removes the nulls and finally we return an array of the indexes for where any of the digits of the number is the same as num.
You can inject this method to your array prototype like this:
Array.prototype.filterMapIndex = function(expression){
const indexs = []
this.filter((newval,index,full)=>{
if(expression(newval,index,full)) indexs.push(index)
})
return indexs
}
next, you can use it simply by calling method :
let myArray = [1,2,3,4,0,3];
const indexes = myArray.filterMapIndex((val)=>{ return val>0 })
Array.prototype.filterMapIndex = function(expression){
const indexs = []
this.filter((newval,index,full)=>{
if(expression(newval,index,full)) indexs.push(index)
})
return indexs
}
let myArray = [1,2,3,4,0,3];
const indexes = myArray.filterMapIndex((val)=>{ return val>0 })
console.log(indexes)
I'm writing a function to pass the test that have array contains number and string.
Here is the test cases average-numner.test.js:
var average = require("./get-average");
test("Average", function() {
var numbers = [4, "-", 8, 11, "hello", "57", 0, 2];
var expected = 5;
var output = average(numbers);
expect(output).toEqual(expected);
});
Here is the function that I wrote average-number.js:
// the input is an array of numbers and strings
// return the average of all the numbers
// be sure to exclude the strings
function averageNumbers(str) {
let sum = 0;
let newArr = [];
var filtered = str.filter(function(item) {
return parseInt(item);
});
return filtered;
}
console.log(averageNumbers([4, "-", 8, 11, "hello", "57", 0, 2]));
// module.exports = averageNumbers;
I achieved that I got new array with only number but it still have string "57" in my filtered array. How can I get rid of it and find sum to get average number?
function averageNumbers(arr) {
var filter = arr.filter(item => typeof item === 'number');
var sum = filter.reduce((acc, n) => acc + n, 0);
return sum / filter.length;
}
console.log(averageNumbers([4, "-", 8, 11, "hello", "57", 0, 2]));
// module.exports = averageNumbers;
Which gives you expected 5
Map and filter
Note I changed the variable name str to arr since it is not a string.
I test for type and whether or not the number is finite and added the rest of the calculation
The code now returns the expected 5
// the input is an array of numbers and strings
// return the average of all the numbers
// be sure to exclude the strings
function averageNumbers(arr) {
const filtered = arr.filter(item => typeof item === 'number' && isFinite(item))
const sum = filtered.reduce((a,b) => a+b)
return +parseFloat(sum/filtered.length).toPrecision(12); // this can be ugly
}
console.log(averageNumbers([4, "-", 8, 11, "hello", "57", 0, 2]));
console.log(averageNumbers([3, "-", 4, 11, "hello", "57", 0, 2, 3]));
Just a reduce returning an object to see the sub parts
// the input is an array of numbers and strings
// return the average of all the numbers
// be sure to exclude the strings
const averageNumbers = arr => {
const averageObject = arr.reduce((acc,item,i) => {
if (typeof item === 'number' && isFinite(item)) {
acc.sum+=item;
acc.nofItems++;
}
if (i===arr.length-1) acc.average = acc.sum/acc.nofItems;
return acc;
},{sum:0,nofItems:0, average:0})
return averageObject;
}
const ave1 = averageNumbers([4, "-", 8, 11, "hello", "57", 0, 2]);
console.log(`Average of ${ave1.nofItems} numeric items was ${ave1.average}. The sum was ${ave1.sum}`)
const ave2 = averageNumbers([3, "-", 4, 11, "hello", "57", 0, 2, 3]);
console.log(`Average of ${ave2.nofItems} numeric items was ${ave2.average}. The sum was ${ave2.sum}`)
filter only checks if the condition is truthy for the given element, and keeps it if so. But it keeps the original value, not the output of the predicate function. If all you want to be able to do is sum the numbers, this should work:
var filtered = str.filter(function (item) {
return parseInt(item);
}).map(item => parseInt(item));
However, if a number is parsed as a 0, it will be considered falsy and filter will drop it. That's okay for computing a sum, because the 0 makes no difference, but if you want to keep it you can do something like:
const filtered = str.map(item => parseInt(item))
.filter(item => item !== NaN);
This will attempt to parse all values, and keep only the values that successfully parse, including existing integers.
You can use reduce and inside callback use typeof to check if the element is a number of not. The accumulator object consist of three keys, total,count and average.
function averageNumbers(c) {
return c.reduce(function(a, b) {
"number" === typeof b && (a.total += b, a.count += 1, a.average = a.total / a.count);
return a;
}, {
total: 0,
count: 0,
average: 0
}).average;
};
console.log(averageNumbers([4, '-', 8, 11, 'hello', '57', 0, 2]));
Given an object and a key, I am creating a function that returns an array containing all the elements of the array located at the given key that are less than 100. Basically, If the array is empty, it should return an empty array. If the array contains no elements less than 100, it should return an empty array.
If the property at the given key is not an array, it should return an empty array.
If there is no property at the key, it should return an empty array.
Here are my codes so far:
function getElementsLessThan100AtProperty(obj, key) {
if (obj.key < 100) {
return obj.key;
}
}
var obj = {
key: [1000, 20, 50, 500]
};
var output = getElementsLessThan100AtProperty(obj, 'key');
console.log(output); // --> MUST RETURN [20, 50]
Any idea what am I missing?
Use the filter method to help with this.
Note: Mozilla JavaScript Docs
The filter() method creates a new array with all elements that pass the test implemented by the provided function.
Something like this should do the trick:
var obj = {
key: [1000, 20, 50, 500]
};
var output = obj['key'].filter(function(item){
return item < 100;
});
console.log(output); // --> MUST RETURN [20, 50]
The same can be shortened using the ES6 arrow function and an implicit return.
var output = obj['key'].filter(item => item < 100);
Using filter with arrow function will make your code much shorter.
var obj = {
key: [1000, 20, 50, 500],
};
console.log(obj['key'].filter(item => item < 100));
You can also use reduce to check if elements are less than 100, then push the value to the accumulator.
var obj = {
key: [1000, 20, 50, 500],
};
var output = obj['key'].reduce((acc, curr) => {
if (curr < 100) acc.push(curr);
return acc;
}, []);
console.log(output);
Array justPrices has values such as:
[0] = 1.5
[1] = 4.5
[2] = 9.9.
How do I return the smallest value in the array?
The tersest expressive code to find the minimum value is probably rest parameters:
const arr = [14, 58, 20, 77, 66, 82, 42, 67, 42, 4]
const min = Math.min(...arr)
console.log(min)
Rest parameters are essentially a convenient shorthand for Function.prototype.apply when you don't need to change the function's context:
var arr = [14, 58, 20, 77, 66, 82, 42, 67, 42, 4]
var min = Math.min.apply(Math, arr)
console.log(min)
This is also a great use case for Array.prototype.reduce:
const arr = [14, 58, 20, 77, 66, 82, 42, 67, 42, 4]
const min = arr.reduce((a, b) => Math.min(a, b))
console.log(min)
It may be tempting to pass Math.min directly to reduce, however the callback receives additional parameters:
callback (accumulator, currentValue, currentIndex, array)
In this particular case it may be a bit verbose. reduce is particularly useful when you have a collection of complex data that you want to aggregate into a single value:
const arr = [{name: 'Location 1', distance: 14}, {name: 'Location 2', distance: 58}, {name: 'Location 3', distance: 20}, {name: 'Location 4', distance: 77}, {name: 'Location 5', distance: 66}, {name: 'Location 6', distance: 82}, {name: 'Location 7', distance: 42}, {name: 'Location 8', distance: 67}, {name: 'Location 9', distance: 42}, {name: 'Location 10', distance: 4}]
const closest = arr.reduce(
(acc, loc) =>
acc.distance < loc.distance
? acc
: loc
)
console.log(closest)
And of course you can always use classic iteration:
var arr,
i,
l,
min
arr = [14, 58, 20, 77, 66, 82, 42, 67, 42, 4]
min = Number.POSITIVE_INFINITY
for (i = 0, l = arr.length; i < l; i++) {
min = Math.min(min, arr[i])
}
console.log(min)
...but even classic iteration can get a modern makeover:
const arr = [14, 58, 20, 77, 66, 82, 42, 67, 42, 4]
let min = Number.POSITIVE_INFINITY
for (const value of arr) {
min = Math.min(min, value)
}
console.log(min)
Jon Resig illustrated in this article how this could be achieved by extending the Array prototype and invoking the underlying Math.min method which unfortunately doesn't take an array but a variable number of arguments:
Array.min = function( array ){
return Math.min.apply( Math, array );
};
and then:
var minimum = Array.min(array);
I find that the easiest way to return the smallest value of an array is to use the Spread Operator on Math.min() function.
return Math.min(...justPrices);
//returns 1.5 on example given
The page on MDN helps to understand it better: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/min
A little extra:
This also works on Math.max() function
return Math.max(...justPrices);
//returns 9.9 on example given.
Hope this helps!
Update: use Darin's / John Resig answer, just keep in mind that you dont need to specifiy thisArg for min, so Math.min.apply(null, arr) will work just fine.
or you can just sort the array and get value #1:
[2,6,7,4,1].sort()[0]
[!] But without supplying custom number sorting function, this will only work in one, very limited case: positive numbers less than 10. See how it would break:
var a = ['', -0.1, -2, -Infinity, Infinity, 0, 0.01, 2, 2.0, 2.01, 11, 1, 1e-10, NaN];
// correct:
a.sort( function (a,b) { return a === b ? 0 : a < b ? -1: 1} );
//Array [NaN, -Infinity, -2, -0.1, 0, "", 1e-10, 0.01, 1, 2, 2, 2.01, 11, Infinity]
// incorrect:
a.sort();
//Array ["", -0.1, -2, -Infinity, 0, 0.01, 1, 11, 1e-10, 2, 2, 2.01, Infinity, NaN]
And, also, array is changed in-place, which might not be what you want.
Imagine you have this array:
var arr = [1, 2, 3];
ES6 way:
var min = Math.min(...arr); //min=1
ES5 way:
var min = Math.min.apply(null, arr); //min=1
If you using D3.js, there is a handy function which does the same, but will ignore undefined values and also check the natural order:
d3.max(array[, accessor])
Returns the maximum value in the given array using natural order. If
the array is empty, returns undefined. An optional accessor function
may be specified, which is equivalent to calling array.map(accessor)
before computing the maximum value.
Unlike the built-in Math.max, this method ignores undefined values;
this is useful for ignoring missing data. In addition, elements are
compared using natural order rather than numeric order. For example,
the maximum of the strings [“20”, “3”] is “3”, while the maximum of
the numbers [20, 3] is 20.
And this is the source code for D3 v4:
export default function(values, valueof) {
var n = values.length,
i = -1,
value,
max;
if (valueof == null) {
while (++i < n) { // Find the first comparable value.
if ((value = values[i]) != null && value >= value) {
max = value;
while (++i < n) { // Compare the remaining values.
if ((value = values[i]) != null && value > max) {
max = value;
}
}
}
}
}
else {
while (++i < n) { // Find the first comparable value.
if ((value = valueof(values[i], i, values)) != null && value >= value) {
max = value;
while (++i < n) { // Compare the remaining values.
if ((value = valueof(values[i], i, values)) != null && value > max) {
max = value;
}
}
}
}
}
return max;
}
ES6 is the way of the future.
arr.reduce((a, b) => Math.min(a, b));
I prefer this form because it's easily generalized for other use cases
var array =[2,3,1,9,8];
var minvalue = array[0];
for (var i = 0; i < array.length; i++) {
if(array[i]<minvalue)
{
minvalue = array[i];
}
}
console.log(minvalue);
Possibly an easier way?
Let's say justPrices is mixed up in terms of value, so you don't know where the smallest value is.
justPrices[0] = 4.5
justPrices[1] = 9.9
justPrices[2] = 1.5
Use sort.
justPrices.sort();
It would then put them in order for you. (Can also be done alphabetically.) The array then would be put in ascending order.
justPrices[0] = 1.5
justPrices[1] = 4.5
justPrices[2] = 9.9
You can then easily grab by the first index.
justPrices[0]
I find this is a bit more useful than what's proposed above because what if you need the lowest 3 numbers as an example? You can also switch which order they're arranged, more info at http://www.w3schools.com/jsref/jsref_sort.asp
function smallest(){
if(arguments[0] instanceof Array)
arguments = arguments[0];
return Math.min.apply( Math, arguments );
}
function largest(){
if(arguments[0] instanceof Array)
arguments = arguments[0];
return Math.max.apply( Math, arguments );
}
var min = smallest(10, 11, 12, 13);
var max = largest([10, 11, 12, 13]);
console.log("Smallest: "+ min +", Largest: "+ max);
I think I have an easy-to-understand solution for this, using only the basics of javaScript.
function myFunction() {
var i = 0;
var smallestNumber = justPrices[0];
for(i = 0; i < justPrices.length; i++) {
if(justPrices[i] < smallestNumber) {
smallestNumber = justPrices[i];
}
}
return smallestNumber;
}
The variable smallestNumber is set to the first element of justPrices, and the for loop loops through the array (I'm just assuming that you know how a for loop works; if not, look it up). If an element of the array is smaller than the current smallestNumber (which at first is the first element), it will replace it's value. When the whole array has gone through the loop, smallestNumber will contain the smallest number in the array.
Here’s a variant of Darin Dimitrov’s answer that doesn’t modify the Array prototype:
const applyToArray = (func, array) => func.apply(Math, array)
applyToArray(Math.min, [1,2,3,4]) // 1
applyToArray(Math.max, [1,2,3,4]) // 4
function tinyFriends() {
let myFriends = ["Mukit", "Ali", "Umor", "sabbir"]
let smallestFridend = myFriends[0];
for (i = 0; i < myFriends.length; i++) {
if (myFriends[i] < smallestFridend) {
smallestFridend = myFriends[i];
}
}
return smallestFridend
}
A super-easy way to find the smallest value would be
Array.prototype.min = function(){
return Math.min.apply(Math,this);
};
To call the function, just use the name of the array and add .min()
Array.prototype.min = function(){
return Math.min.apply(Math,this);
};
var arr = [12,56,126,-1,5,15];
console.log( arr.min() );
If you are using Underscore or Lodash you can get the minimal value using this kind of simple functional pipeline
_.chain([7, 6, -1, 3, 2]).sortBy().first().value()
// -1
You also have the .min function
_.min([7, 6, -1, 3, 2])
// -1
Here is code that will detect the lowest value in an array of numbers.
//function for finding smallest value in an array
function arrayMin(array){
var min = array[0];
for(var i = 0; i < array.length; i++){
if(min < array[i]){
min = min;
}else if (min > array[i]){
min = array[i + 1];
}else if (min == array[i]){
min = min;
}
}
return min;
};
call it in this way:
var fooArray = [1,10,5,2];
var foo = arrayMin(fooArray);
(Just change the second else if result from: min = min to min = array[i]
if you want numbers which reach the smallest value to replace the original number.)
Here is a recursive way on how to do it using ternary operators both for the recursion and decision whether you came across a min number or not.
const findMin = (arr, min, i) => arr.length === i ? min :
findMin(arr, min = arr[i] < min ? arr[i] : min, ++i)
Code snippet:
const findMin = (arr, min, i) => arr.length === i ? min :
findMin(arr, min = arr[i] < min ? arr[i] : min, ++i)
const arr = [5, 34, 2, 1, 6, 7, 9, 3];
const min = findMin(arr, arr[0], 0)
console.log(min);
You can use min method in Math object!
const abc = [50, 35, -25, -6, 91];
function findMin(args) {
return Math.min(...args);
}
console.log(findMin(abc));
For anyone out there who needs this I just have a feeling.
(Get the smallest number with multi values in the array)
Thanks to Akexis answer.
if you have let's say an array of
Distance and ID and ETA in minutes
So you do push maybe in for loop or something
Distances.push([1.3, 1, 2]); // Array inside an array.
And then when It finishes, do a sort
Distances.sort();
So this will sort upon the first thing which is Distance here.
Now we have the closest or the least is the first you can do
Distances[0] // The closest distance or the smallest number of distance. (array).
I liked this question - Legitimate uses of the Function constructor - so I wanted to create a similar question regarding the Array constructor.
Of course, the array literal notation is the correct way to create arrays. This would mean that the new Array notation should not be used. And "case closed".
However, there is one specificity of the new Array form. If a natural number is passed in, an empty array is created and its length property is set to that number.
So
arr = new Array( 7 );
is equivalent to
arr = [];
arr.length = 7;
This can be considered a feature. I was wondering if this "feature" has real-world uses. I recently stumbled upon one such (simple) use:
new Array( n + 1 ).join( '*' ) // returns string containing n stars
// e.g.
new Array( 3 ).join( '*' ) // returns '**'
new Array( 6 ).join( '*' ) // returns '*****'
This is cool, but was hoping for some more advanced uses. (Something that would make the new Array notation a legitimate tool in JavaScript programs.)
Update: I've noticed that the jQuery library uses the new Array( len ) notation in one instance - it's inside the when function (search for "when:"):
when: function( firstParam ) {
var args = sliceDeferred.call( arguments, 0 ),
i = 0,
length = args.length,
pValues = new Array( length ),
count = length,
pCount = length,
// etc.
They use it to initialize the pValues local variable, which is used in a local function further down in the code:
function progressFunc( i ) {
return function( value ) {
pValues[ i ] = arguments.length > 1 ?
sliceDeferred.call( arguments, 0 ) : value;
deferred.notifyWith( promise, pValues );
};
}
I would love to know if changing the assignment to just
pValues = [],
would break the program... (Is new Array( length ) required for notifyWith to work properly?)
I don't know if this counts, but one case where you'd use the constructor is if you need to be sure you have clean, unmodified Array constructor. You can create an "iframe sandbox"
var iframe = document.createElement("iframe");
iframe.style.display = "none";
document.body.appendChild(iframe);
var Safe = frames[frames.length - 1];
And then create arrays like this...
var things = new Safe.Array('x', 'y', 'z');
...knowing that your arrays will not have any foreign stuff in the prototype put there by other scripts.
That's not making use of that single-parameter-as-array-length feature, though. The only thing that's probably really good for is setting up huge arrays to benchmark stuff.
Pretty much anything you can come up with a homebrewn map function (native .map doesn't iterate and jQuery.map is just full bugs)
Creating ranges:
//1-20
map( Array( 20 ), function( v,i ){
return i+1;
});
//[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
//-50 - 0
map( Array( 51 ), function( v,i ){
return i-50;
});
//[-50, -49, -48, -47, -46, -45, -44, -43, -42, -41, -40, -39, -38, -37, -36, -35, -34, -33, -32, -31, -30, -29, -28, -27, -26, -25, -24, -23, -22, -21, -20, -19, -18, -17, -16, -15, -14, -13, -12, -11, -10, -9, -8, -7, -6, -5, -4, -3, -2, -1, 0]
In general, instead of doing:
var a = [],
l = 10;
while ( l-- ) {
a.unshift(
(function(l){
return function() {
alert( l );
};
})( l )
);
}
You can do this:
var a = map( Array( 10 ), function ( v, i ) {
return function(){
alert( i );
};
});
Note that this only applies to jQuery.map or shimmed .map, native .map doesn't iterate the array.
If you're not using jQuery( which flattens the result :( ) you can create
three dimensional arrays like this:
var xyz = map(Array(10), function (v, i) {
return map(Array(10), function (v, j) {
return map(Array(10), function (v, k) {
return i * 100 + j * 10 + k;
});
});
});
xyz[0][0][0] // 0
xyz[9][9][9] // 999
xyz[4][4][4] // 444
xyz[3][5][8] // 358
Of which the equivalent of for loops is pretty horrific :P
Quick implementation of a map function for completeness:
function map( elems, callback ){
var i, length = elems.length, ret = [];
for ( i = 0; i < length; i++ ) {
value = callback( elems[ i ], i );
ret[ ret.length ] = value;
}
return ret;
}
How about as an alternate way to shallow clone an Array?
var arr = [1,2,3];
var arr2 = Array.apply( null, arr );
arr === arr2; // false;
arr.length === arr2.length; // true
Yes, I'm reaching here because you'd just use .slice(), but then I really don't see using Array as illegitimate in the first place, as long as you know what you're doing.
Getting off topic, but one way to make a common function that utilizes Array or slice. Requires bind. Too lazy right now to update for older browsers.
http://jsfiddle.net/fdgBU/1/
var slicer,
apply = Function.prototype.apply;
if( apply.bind ) {
try {
(slicer = apply.bind( Array, null ))({length:0});
} catch( e ) {
slicer = apply.bind([].slice);
}
} else {
slicer = function( coll ) {
if( !coll || coll.length !== +coll.length ) return;
var res = [], i = 0, len = coll.length >>> 0;
for( ; i < len; ++i ) {
res[i] = coll[i];
}
return res;
};
}
var arr_like = {'0':true,'1':true,'2':true,length:3},
arr = slicer( arr_like );
console.log( arr ); // [true, true, true]
console.log( arr.length === arr_like.length); // true