After running a function i am getting an array like this.
["1:s", "2:2", "0:f"]
but i want to convert this array like this
["0:f","1:s","2:2"]
i mean index should be same as key.
You could just sort it with taking the index out of the string.
var array = ["1:s", "2:2", "0:f"];
array.sort(function (a, b) {
return a.split(':')[0] - b.split(':')[0];
});
console.log(array);
Related
I want to create a function to find the lowest value within a set of numbers, but I do not wish to use the Math.min(); method. Below is my code I have constructed:
function min(arr) {
var lowest = arr.sort((x, y) => x - y);
return lowest[0];
}
but 'arr.sort' is not a function, as it has not been defined for obvious reasons: I want to be able to input any array into the 'min' function.
I tried creating a JavaScript function for finding the lowest value in an array of numbers, expecting to have a function that would accept any array and would output the lowest value in that array.
I want to create a function to find the lowest value within a set of numbersfunction to find the lowest value within a set of numbers
Just pop the sorted array
That is assuming you are calling your function with an actual array and you do not mind that array is modified
const min = arr => arr.sort((a, b) => b - a).pop();
console.log(min([7,6,8,99,100]))
console.log(min([1000,999,998,997]))
const arr1 = [1000,999,998,997]
console.log("---------------")
console.log(arr1)
console.log(min(arr1))
console.log(arr1)
function min(arr) {
arr.sort( (a, b) => a - b );
return arr[0]
}
Pay attention, though, that sort() overwrites the original array.
If I have an array of:
var arr = [{"apple":3}, {"pear":5}, {"orange":1}]
How can I sort this array based on the number value inside the objects desc order?
I want the sorted array to be:
[{"pear":5}, {"apple":3}, {"orange":1}]
Try this.
const newArr = arr.sort((a, b) => {
return Object.values(b)[0] - Object.values(a)[0];
});
You need to create another variable, then run the array variable with .reverse(); at the end.
Just a reference for you,waiting for more elegant solution to it
var arr = [{"apple":3}, {"pear":5}, {"orange":1}]
arr.sort((a,b)=>{
//return b[Object.keys(b)[0]] - a[Object.keys(a)[0]]
return Object.values(b)[0] - Object.values(a)[0];
})
console.log(arr)
I have an array that looks like this:
0123456789123456:14
0123456789123456:138
0123456789123456:0
Basically I need to sort them in order from greatest to least, but sort by the numbers after the colon. I know the sort function is kind of weird but im not sure how I would do this without breaking the id before the colon up from the value after.
Split the string get the second value and sort by the delta.
const second = s => s.split(':')[1];
var array = ['0123456789123456:14', '0123456789123456:138', '0123456789123456:0'];
array.sort((a, b) => second(b) - second(a));
console.log(array);
Assuming the structure of the items in the array is known (like described), you could sort it like this.
const yourArray = ['0123456789123456:14', '0123456789123456:138', '0123456789123456:0'];
yourArray.sort((a, b) => (b.split(':')[1] - a.split(':')[1]));
console.log(yourArray);
You can use sort() and reverse(), like this (try it in your browser console):
var arrStr = [
'0123456789123456:14',
'0123456789123456:138',
'0123456789123456:0'
];
arrStr.sort();
console.log(arrStr);
arrStr.reverse();
console.log(arrStr);
You can use below helper to sort array of strings in javascript:
data.sort((a, b) => a[key].localeCompare(b[key]))
I have 2 multidimensional arrays:
[[230.0], [10.0], [12.0]]
[[50.0], [60.0], [89.0]]
And am trying to sum each element together and keep the same array structure. So it should look like:
[[280.0], [70.0], [101.0]]
I tried this:
var sum = array1.map(function (num, index) {
return num + array2[index];
});
But I get this:
[23050, 1060, 1289]
Any help would be appreciated. Thanks.
The code, you use, takes only a single level, without respecting nested arrays. By taking na array with only one element without an index of the inner array and using an operator, like +, the prototype function toString is invoced and a joined string (the single element as string, without , as separator) is returned and added. The result is a string , not the result of a numerical operation with +.
You could take a recursive approach and check if the value is an array, then call the function again with the nested element.
function sum(a, b) {
return a.map((v, i) => Array.isArray(v) ? sum(v, b[i]) : v + b[i]);
}
console.log(sum([[230], [10], [12]], [[50], [60], [89]]))
Make it like this
var sum = array1.map(function (num, index) {
return parseInt(num) + parseInt(array2[index]);
});
You should have to make parseInt or parseFloat so it can convert string with them
STEPS
Iterate through every number in the array (array length).
Sum the objects of the same index in both of the arrays.
Push the sum into another array for the result. Use parseFloat if the input is string.
(Optional) use .toFixed(1) to set decimal place to have 1 digit.
const arr1 = [[230.0], [10.0], [12.0]]
const arr2 = [[50.0], [60.0], [89.0]]
let sum = []
for (let i = 0; i < arr1.length; i++){ // Assume arr1 and arr2 have the same size
let eachSum = parseFloat(arr1[i]) + parseFloat(arr2[i])
sum.push([eachSum.toFixed(1)])
}
console.log(sum)
You are trying to add two arrays structures inside the map function.
so one solution so you can see what is happening is this...
array1.map((a,i) => a[0] + array2[i][0])
screenshot from the console...
Inside map fn you should:
return parseInt(num) + parseInt(array2[index]);
This is happening because when you are trying to add them, these variable are arrays and not integers. So they are evaluated as strings and concatenated.
I have an object like this:
I would like to do two things.
Sort the properties based on their values
I would to know the order (or index) for any given property. For example, after ordering, I would like to know that the index of 00D is the 5th.
How can I achieve this in JavaScript?
While you can not sort properties of an object, you could use an array of keys of the object, sort them and take the wanted element, you want.
var keys = Object.keys(object), // get all keys
indices = Object.create(null); // hash table for indices
// sort by value of the object
keys.sort(function (a, b) { return object[a] - object[b]; });
// create hash table with indices
keys.forEach(function (k, i) { indices[k] = i; });
// access the 5th key
console.log(keys[5]);
// get index of 00G
console.log(indices['00G']);