Skip to content

Commit b8233ea

Browse files
author
Devendra Parmar
committed
Solved the two questions of the JavaScript
1. Get the max elements from the given array 2. Get the median elements from the given array
1 parent 8ab86f6 commit b8233ea

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
// Write a JavaScript program to get the n maximum elements from the provided array. If n is greater than or equal to the provided array's length, return the original array (sorted in descending order).
2+
3+
const maxElem = (arr, n = 1) => {
4+
return [...arr].sort((a, b) => b - a).slice(0, n);
5+
};
6+
7+
const prompt = require("prompt-sync")();
8+
9+
var size = parseInt(prompt("Enter The Array Size : "));
10+
11+
var arr = [];
12+
13+
console.log("Enter Array Elements : ");
14+
for (let i = 0; i < size; i++) {
15+
var elem = parseInt(prompt(`[${i}] : `));
16+
arr.push(elem);
17+
}
18+
19+
var ele = parseInt(prompt("Enter How Many Element You Want Find : "));
20+
21+
var ans = maxElem(arr, ele);
22+
23+
console.log(ans);

October/GetTheMedianOfArray.js

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
// Write a JavaScript program to get the median of an array of numbers.
2+
3+
// Note: Find the middle of the array, use Array.sort() to sort the values. Return the number at the midpoint if length is odd, otherwise the average of the two middle numbers.
4+
5+
const midElem = (arr) => {
6+
const mid = Math.floor(arr.length / 2),
7+
num = [...arr].sort((a, b) => a - b);
8+
return arr.length % 2 !== 0 ? num[mid] : (num[mid - 1] + num[mid]) / 2;
9+
};
10+
11+
const prompt = require("prompt-sync")();
12+
13+
var size = parseInt(prompt("Enter Array Size : "));
14+
15+
var arr = [];
16+
17+
console.log("Enter Array Elements : ");
18+
for (let i = 0; i < size; i++) {
19+
var elem = parseInt(prompt(`[${i}] : `));
20+
arr.push(elem);
21+
}
22+
23+
var mid = midElem(arr);
24+
25+
console.log(mid);

0 commit comments

Comments
 (0)