#javascript #arrays #dictionary #filter #tuples
#javascript #массивы #словарь #Фильтр #Кортежи
Вопрос:
У меня есть два списка и I, и мне нужно вернуть только первое число кортежей в нечетной позиции, в которой сумма кортежей больше 70. Пример кортежей: [[2,70],[3,71],[4,72],[5,73]] возврат [[3],[5]]
Кажется, я прав в оценке первой части (суммирую кортеж, превышающий 70, и получаю нечетную позицию), но не могу заставить его вернуть первый элемент. Ребята, вы можете мне помочь?
const range = (from, to) => {
let arr = [];
for (let i = from; i <= to; i ){
arr.push(i);
}
return arr
}
const ternary = fn => (a, b) => fn(a, b) ? a : b
const not = (fn) => (...args) => !fn(...args)
const greaterThan = num1 => num2 => num1 > num2 ? true : false
const longestList = (arr1, arr2) => arr1.length>arr2.length ? arr1 : arr2
const tupla = (a,b) => [a,b]
const esImpar = num => num % 2 !== 0
const zipped = (list1, list2) => {
return ternary(not(longestList))(range(1,50),range(51,80))
.map((element, index)=>{
return tupla(list1[index],list2[index])
/* return element */
})
}
//tuples in odd position that
const newArray = zipped(range(1,50),range(51,80))
.map((element, index)=>{
return element[0] element[1] // return sum of the elements of the array
})
.filter(not(greaterThan(70))) // filters greater than 70
.filter((element, index)=>{ // filters odd elements
return esImpar(index)
})
console.log(newArray)
Комментарии:
1. что
newArray
должно содержаться в нем?
Ответ №1:
Вы действительно близки, но вам нужно немного изменить порядок ваших методов цепочки массивов, и вы должны изменить свой фильтр для чисел до 70, чтобы он вычислял встроенную сумму. Таким образом, у вас все еще есть доступ к исходным элементам после запуска фильтра.
Так, например, шаги должны быть:
- Отфильтруйте четные элементы.
- Отфильтруйте элементы, сумма которых меньше 70.
- Сопоставьте каждый элемент, чтобы получить первый элемент.
С этой целью вы можете изменить свой фрагмент следующим образом:
const range = (from, to) => {
let arr = [];
for (let i = from; i <= to; i ){
arr.push(i);
}
return arr
}
const ternary = fn => (a, b) => fn(a, b) ? a : b
const not = (fn) => (...args) => !fn(...args)
const greaterThan = num1 => num2 => num1 > num2 ? true : false
const longestList = (arr1, arr2) => arr1.length>arr2.length ? arr1 : arr2
const tupla = (a,b) => [a,b]
const esImpar = num => num % 2 !== 0
const zipped = (list1, list2) => {
return ternary(not(longestList))(range(1,50),range(51,80))
.map((element, index)=>{
return tupla(list1[index],list2[index])
/* return element */
})
}
// Replacing input with your test case:
const newArray = [[2,70],[3,71],[4,72],[5,73]]
// This map will not help you, it destroys the information about specific elements.
// .map((element, index)=>{ return element[0] element[1] })
// This is good, but needs to calculate the sum inline!
// My inline calculation looks complicated, but its not that bad.
// You can clean it up if you like.
.filter(item => not(greaterThan(70))(item.reduce((a, b) => a b, 0))) // filters greater than 70
// Good as is.
.filter((element, index) => { return esImpar(index) })
// Finally, just map each item to an array containing only the first element:
.map(element => [element[0]])
console.log(newArray)
Или, как более короткий фрагмент, то же самое:
// [[2,70],[3,71],[4,72],[5,73]] return [[3],[5]]
const input_array = [[2,70],[3,71],[4,72],[5,73]];
const result_array = input_array
.filter((_, i) => i % 2 === 1) // Filter out even indices
.filter(item => item.reduce((a, b) => a b, 0) >= 70) // Filter items who's sum is under 70.
.map(item => [item[0]]) // Map items to get first element.
console.log(result_array);
Ответ №2:
Вот вы (начиная с вашего ввода):
[[2,70],[3,71],[4,72],[5,73]]
.filter((_,i) => i%2) // only the ones in the odd posiitons
.filter(el => el[0] el[1] >= 70) // only the ones with the sum of the two elements greater than 70
.map(el => [el[0]]) // map to an array of arrays with the first element only