JavaScript Second Largest Element in array Error in code [duplicate] - javascript

This question already has answers here:
Why doesn't the sort function of javascript work well?
(5 answers)
Closed 2 years ago.
I wrote this code to get second max...it worked in cases like nums=[1,2,3,2,4] and i got second max equal to 3.But if mu array is [1,2,3,4,5,6,7,8,9,10] the output for second max is 8.
Please help.
function getSecondLargest(arr){
let uniqueArr = [ ...new Set(arr) ];
uniqueArr.sort();
const z= uniqueArr.length;
return arr[z-2];
}

try this
let intArray =[1,2,3,4,5,6,7,8,9,10];
console.log(intArray.sort((a, b) => b - a)[1]);

Try this:
let arr = [1,2,3,4,5,6,7,8,9,10];
function getSecondLargest(nums){
let sort = arr.sort((a, b) => a - b);
return sort[sort.length - 2]
}
console.log(getSecondLargest(arr));

It is returning 8 because sort() method in javascript by default sorts the array in alphabetical order, so applying sort() method to your will return something like this:-
[1,10,2,3,4,5,6,7,8,9]
So, in order to sort them numerically, you've to add this new method which is further simplified by using arrows functions in ES6. Following will be your updated code:-
function getSecondLargest(arr){
let uniqueArr = [ ...new Set(arr) ];
uniqueArray.sort((a,b) => a-b);
const z= uniqueArr.length;
return arr[z-2];
}

It is sorting the elements alphabetically. Try passing the function in the sort:
let arr1 = [1,2,3,2,4];
let arr2 = [1,2,3,4,5,6,7,8,9,10];
console.log( getSecondLargest(arr1) );
console.log( getSecondLargest(arr2) );
function getSecondLargest(arr){
let uniqueArr = [ ...new Set(arr) ];
uniqueArr.sort((a,b)=> a-b);
const z= uniqueArr.length;
return arr[z-2];
}
I recommend you take care of edge cases such as arrays of length 0 or 1...

Related

How to return a multidimensional array of numbers in descending order?

I am new to JS and I am tring to sort a multidimensional array and I want to return the array in descending order -
Input -
let input = [[1,2,3],[1,3,2],[3,2,1],[3,1,2],[2,1,3],[2,3,1]]
Expected Ouput
[[3,2,1],[3,1,2],[2,3,1],[2,1,3],[1,3,2],[1,2,3]]
I have tried sort
let result = input.sort((a, b) => a - b)
But I am getting the same array sent back to me
[[1,2,3],[1,3,2],[3,2,1],[3,1,2],[2,1,3],[2,3,1]]
I have also tried a for loop with the sort method
for(let i = 0; i < input.length; i++){
let inputArr = input[i]
let output = inputArr.sort((a,b) => a - b)
console.log(output)
}
But I get returned
[1,2,3] 6 times (the length of the original array?)
How do I return the array values in descending order?
Thanks
You need to compare the subarray items against each other - .sort((a, b) -> a - b) makes no sense because a and b are arrays, and so can't be meaningfully subtracted from each other.
let input = [[1,2,3],[1,3,2],[3,2,1],[3,1,2],[2,1,3],[2,3,1]];
input.sort((a, b) => {
// Find the first index that's different between the two subarrays being compared
const diffIndex = a.findIndex((itemA, i) => b[i] !== itemA);
// Return the difference, so that the higher value will come first in the result
// If no difference found, return 0 (so they will come next to each other)
return diffIndex === -1 ? 0 : b[diffIndex] - a[diffIndex];
});
console.log(input);
That's assuming that the subarrays contain the same number of values, as it is in the example.
The sort operation expects numbers. You can apply the .sort() array method on input using concatenated inner array elements converted into a number - +arr.join('') - as in the following demo:
let input = [ [1,2,3], [1,3,2], [3,2,1], [3,1,2], [2,1,3], [2,3,1] ];
const sorted = input.sort( (a,b) => +b.join('') - +a.join('') );
console.log( sorted );
//OUTPUT: [ [3,2,1], [3,1,2], [2,3,1], [2,1,3], [1,3,2], [1,2,3] ]
NOTE
You may also use parseInt( arr.join('') ) in place of +arr.join('').

Finding match element with array reduce [duplicate]

This question already has answers here:
How to get the difference between two arrays in JavaScript?
(84 answers)
Closed 2 years ago.
I have two arrays
a. [1,2,3,4,5]
b. [2,3,4,5,6]
I try to find 2,3,4,5 with array.reduce because I think it is more efficient.
Can I do so?
This will get you the same result without using reduce:
var a=[1,2,3,4,5];
var b= [2,3,4,5,6];
result = a.filter(p=>b.includes(p));
console.log(result);
Or with reduce:
var a=[1,2,3,4,5];
var b= [2,3,4,5,6];
var result = b.reduce((acc,elem)=>{
if(a.includes(elem)) acc.push(elem);
return acc;
},[]);
console.log(result);
With filter and includes
{
const a = [1,2,3,4,5];
const b = [2,3,4,5,6];
let overlap = a.filter(e => b.includes(e))
console.log(overlap)
}

How to sort an array using regex in Javascript? [duplicate]

This question already has answers here:
Natural sort of alphanumerical strings in JavaScript
(6 answers)
Closed 2 years ago.
I have an array which looks like this
arr = ["#0abc", "#2egf", "#0pol kol", "#1loa", "#2ko pol"]
As you can see, each element in the array has #n associated with it where n is any number between 0-9. Now based on the n, I want to sort by array in ascending order such that the final output looks like this
[ '#0abc', '#0pol kol', '#1loa', '#2egf', '#2ko pol' ]
So this is what I do
rankWordMap = {}
finalArr = []
arr.forEach(function(entry) {
rank = entry.charAt(1)
if(rankWordMap[rank]) {
rankWordMap[rank].push(entry);
}
else {
rankWordMap[rank] = [entry];
}
})
for (var key in rankWordMap) {
if (rankWordMap.hasOwnProperty(key)) {
finalArr.push(...rankWordMap[key])
}
}
console.log(finalArr)
I get the expected output but as you can see, it's pretty inefficient. Besides I could have hundreds of elements sometimes where I would like to quickly sort it rather than doing it this way.
Is there any shorter way to implement this? I am specifically looking for a regex solution but other solutions are fine too.
No need for regex, just sort based on the integer value of the second character in each entry:
arr = ["#0abc", "#2egf", "#0pol kol", "#1loa", "#2ko pol"];
arr.sort((a, b) => parseInt(a[1]) - parseInt(b[1]));
console.log(arr);
You could match the first coming digits and take this value for sorting.
var
getValue = string => string.match(/\d+/),
array = ["#0abc", "#2egf", "#0pol kol", "#1loa", "#2ko pol"];
array.sort((a, b) => getValue(a) - getValue(b));
console.log(array);

How do I get multiple index on an Array

I am trying to get multiple index positions on an Array for a Boolean value.
I have tried applying a loop using while and for to iterate more then one index position with no success so far.
Here is my code:
let jo = [1,2,3,4,5]
let ji = [1,2,3]
let checker = (arr1,arr2) => {
let falsy = arr1.every(num => arr2.includes(num)) == false ?
arr1.map(falsy => arr2.includes(falsy)) : "tba";
//the block below is the frustrated attempt:
let i = falsy.indexOf(false);
while(i>=0){
return falsy.findIndex(ih => ih == false)
}
}
console.log(checker(jo,ji))
I would like to get the index where false occurs stored in a variable that has iterated over all array so I can use this variable to return just the false values on falsy like this:
return falsy[i] = [4,5]
Then after that I will add more to the first if statement to check both arr1 x arr2 or arr2 x arr1
Thanks in advance!
It looks like you're attempting to get the difference between two arrays. This is a fairly comment use-case for Sets. In this case, your code would look like this:
let jo = [1,2,3,4,5]
let ji = [1,2,3]
const checker = (arr1, arr2) => {
return new Set(arr1.filter(x => !new Set(arr2).has(x)))
}
console.log(checker(jo, ji)); // {4, 5}
If you wanted to get the indexes of the differences, you would need to apply a map to the result of the new Set like so:
const checker = (arr1, arr2) => {
const difference = new Set(arr1.filter(x => !new Set(arr2).has(x)));
return Array.from(difference).map(value => arr1.indexOf(v));
}

Javascript - Rearrange array elements in ascending order of elements within each array

I have an array:
arr =
[{"nid":"MIA","keys":[{"sid":"sm1"},{"sid":"sm2"}]},
{"nid":"MID","keys":[{"sid":"sm1"}]},
{"nid":"MIT","keys":[{"sid":"sm1"},{"sid":"sm2"},{"sid":"sm3"},{"sid":"sm4"},{"sid":"sm5"},{"sid":"sm6"},{"sid":"sm7"},{"sid":"sm8"},{"sid":"sm9"},{"sid":"sm10"}]},
{"nid":"MIO","keys":[{"sid":"sm1"},{"sid":"sm2"},{"sid":"sm3"}]},
{"nid":"MIS","keys":[{"sid":"sm1"},{"sid":"sm2"}]},
{"nid":"MIH","keys":[{"sid":"sm1"}]}]
arr consists of 6 elements. Each of these six elements consists of another array keys. I need to rearrange the six elements in ascending order of the number of keys within each. This means that I need the array to be rearranged in this manner:
arr =
[
{"nid":"MID","keys":[{"sid":"sm1"}]},
{"nid":"MIH","keys":[{"sid":"sm1"}]},
{"nid":"MIA","keys":[{"sid":"sm1"},{"sid":"sm2"}]},
{"nid":"MIS","keys":[{"sid":"sm1"},{"sid":"sm2"}]},
{"nid":"MIO","keys":[{"sid":"sm1"},{"sid":"sm2"},{"sid":"sm3"}]},
{"nid":"MIT","keys":[{"sid":"sm1"},{"sid":"sm2"},{"sid":"sm3"},{"sid":"sm4"},{"sid":"sm5"},{"sid":"sm6"},{"sid":"sm7"},{"sid":"sm8"},{"sid":"sm9"},{"sid":"sm10"}]},
]
I tried to get the number of elements within keys of each array element as shown in the code below:
var arrMap = [];
arr.forEach(function(array_) {
key_ = array_.keys;
var count = 0;
key_.forEach(function(arrKey) {
count++;
var keyCode = arrKey.sid;
})
arrMap.push({'nid':array_.nid, 'count': count});
})
console.log(arrMap);
This gave me the following output:
[{"nid":"MIA","count":2},{"nid":"MID","count":1},{"nid":"MIT","count":10},{"nid":"MIO","count":3},{"nid":"MIS","count":2},{"nid":"MIH","count":1}]
Now I am confused as to how I can proceed to rearrange the array using the count of key elements. Any guidance/help would be highly appreciated!
You can try .sort
let arr = [ {"nid":"MIA","keys":[{"sid":"sm1"},{"sid":"sm2"}]},
{"nid":"MID","keys":[{"sid":"sm1"}]},
{"nid":"MIT","keys":[{"sid":"sm1"},{"sid":"sm2"},{"sid":"sm3"},{"sid":"sm4"},{"sid":"sm5"},{"sid":"sm6"},{"sid":"sm7"},{"sid":"sm8"},{"sid":"sm9"},{"sid":"sm10"}]},
{"nid":"MIO","keys":[{"sid":"sm1"},{"sid":"sm2"},{"sid":"sm3"}]},
{"nid":"MIS","keys":[{"sid":"sm1"},{"sid":"sm2"}]},
{"nid":"MIH","keys":[{"sid":"sm1"}]} ];
arr.sort((a, b) => a.keys.length - b.keys.length);
console.log(arr);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
You can achieve this by using sort function of array
arr.sort(function(a,b){return a.keys.length - b.keys.length})

Categories

Resources