Skip to content

Instantly share code, notes, and snippets.

@blacksheep557
Created October 12, 2021 04:13
Show Gist options
  • Select an option

  • Save blacksheep557/95c18e9af2ef2c3ce2ceef932988fb9b to your computer and use it in GitHub Desktop.

Select an option

Save blacksheep557/95c18e9af2ef2c3ce2ceef932988fb9b to your computer and use it in GitHub Desktop.
function sortByLength(arr = []) {
for (let j = 0; j < arr.length; j++) {
for (let i = 0; i < arr.length - j; i++) {
const [x, y] = [arr[i], arr[i + 1]]
if (arr[i + 1] && arr[i].length > arr[i + 1].length) swap(arr, i, i + 1)
}
}
console.log(arr)
return arr
}
function swap(arr, i, j) {
const x = arr[i]
const y = arr[j]
arr[j] = x
arr[i] = y
}
const users = [
{ name: 'John', age: 23, numberOfCars: 1 },
{ name: 'Rahul', age: 50, numberOfCars: 2 },
{ name: 'Clark', age: 98, numberOfCars: 20 },
{ name: 'Dev', age: 90, numberOfCars: 3 },
{ name: 'Elliot', age: 82, numberOfCars: 1 },
{ name: 'Anderson', age: 19, numberOfCars: 5 },
{ name: 'James', age: 41, numberOfCars: 6 },
{ name: 'Chad', age: 32, numberOfCars: 11 },
]
function minDiffAge(userName) {
const userObj = users.filter(({ name }) => name === userName)[0];
if (!userObj) return;
let minDiff = Infinity
let res;
let cars = -Infinity;
users.filter(({ name }) => name !== userName).forEach(({ age, name, numberOfCars }) => {
const currDiff = Math.abs(userObj.age - age)
if (currDiff < minDiff) {
minDiff = currDiff
res = name
cars = numberOfCars
}
if (currDiff === minDiff) {
if (numberOfCars > cars) {
cars = numberOfCars
res = name
}
}
})
console.log(res)
return res
}
minDiffAge('Dev'); // 'Clark'
minDiffAge('Elliot'); // 'Dev'
minDiffAge('Chad'); // 'James'
minDiffAge('Cassey'); // undefined
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment