정렬된 후(오름차순 또는 내림차순으로) 값(두 번째 인수)이 배열(첫 번째 인수)에 삽입되어야 하는 가장 낮은 인덱스를 반환하는 함수를 작성해야 합니다. 반환된 값은 숫자여야 합니다.
예를 들어 getIndexToInsert() −
함수가 있다고 가정해 보겠습니다.getIndexToInsert([1,2,3,4], 1.5, ‘asc’) should return 1 because it is greater than 1 (index 0), but less than 2 (index 1).
마찬가지로
getIndexToInsert([20,3,5], 19, ‘asc’) should return 2 because once the array has been sorted in ascending order it will look like [3,5,20] and 19 is less than 20 (index 2) and greater than 5 (index 1).
따라서 이 함수의 코드를 작성해 보겠습니다 -
예시
const arr = [20, 3, 5];
const getIndexToInsert = (arr, element, order = 'asc') => {
const creds = arr.reduce((acc, val) => {
let { greater, smaller } = acc;
if(val < element){
smaller++;
}else{
greater++;
};
return { greater, smaller };
}, {
greater: 0,
smaller: 0
});
return order === 'asc' ? creds.smaller : creds.greater;
};
console.log(getIndexToInsert(arr, 19, 'des'));
console.log(getIndexToInsert(arr, 19,)); 출력
콘솔의 출력은 다음과 같습니다. -
1 2