Javascript проверяет, существует ли весь элемент массива в массиве JSON

#javascript #arrays #json

#javascript #массивы #json

Вопрос:

Сравните весь элемент массива с объектом массива JSON

 const filterArray = ['Ford', 'Fiat'];

const showrooms = [{
    "Name": "Mark Auto",
    "Location": "Delhi",
    "Cars": ['Ford', 'BMW', 'Fiat']
  },
  {
    "Name": "Cardekho",
    "Location": "Mumbai",
    "Cars": ['Ford', 'Fiat']
  },
  {
    "Name": "Tata Arena",
    "Location": "Pune",
    "Cars": ['Ford', 'BMW']
  },
  {
    "Name": "Nexa Showroom",
    "Location": "Noida",
    "Cars": ['Suzuki', 'Ford', 'Tata', 'Fiat']
  }
]
 

Я пишу код для фильтрации данных, но не работаю.

 const result = this.showrooms.filter(c=> this.filterArray.includes(c.Cars)).map(a=>a.Name);
 

Желаемый результат

 ['Mark Auto', 'Cardekho', 'Nexa Showroom']
 

Ответ №1:

Вы могли every бы проверить, включают ли автомобили каждого демонстрационного зала все автомобили в filterArray

 const filterArray = ['Ford', 'Fiat'];

const showrooms = [
  {
    Name: "Mark Auto",
    Location: "Delhi",
    Cars: ["Ford", "BMW", "Fiat"],
  },
  {
    Name: "Cardekho",
    Location: "Mumbai",
    Cars: ["Ford", "Fiat"],
  },
  {
    Name: "Tata Arena",
    Location: "Pune",
    Cars: ["Ford", "BMW"],
  },
  {
    Name: "Nexa Showroom",
    Location: "Noida",
    Cars: ["Suzuki", "Ford", "Tata", "Fiat"],
  },
];

const res = showrooms
  .filter((s) => filterArray.every((c) => s.Cars.includes(c)))
  .map((s) => s.Name);

console.log(res); 

Ответ №2:

Используйте every

 const filterArray = ['Ford', 'Fiat'];

const showrooms = [{
    "Name": "Mark Auto",
    "Location": "Delhi",
    "Cars": ['Ford', 'BMW', 'Fiat']
  },
  {
    "Name": "Cardekho",
    "Location": "Mumbai",
    "Cars": ['Ford', 'Fiat']
  },
  {
    "Name": "Tata Arena",
    "Location": "Pune",
    "Cars": ['Ford', 'BMW']
  },
  {
    "Name": "Nexa Showroom",
    "Location": "Noida",
    "Cars": ['Suzuki', 'Ford', 'Tata', 'Fiat']
  }
];
const result = showrooms.filter(c => filterArray.every(e => c.Cars.includes(e))).map(a => a.Name);
console.log(result); 

Ответ №3:

Просто нужно обновить условие внутри вашего фильтра. Текущий не возвращается как ожидаемый результат.

 const filterArray = ["Ford", "Fiat"];

const showrooms = [
  {
    Name: "Mark Auto",
    Location: "Delhi",
    Cars: ["Ford", "BMW", "Fiat"],
  },
  {
    Name: "Cardekho",
    Location: "Mumbai",
    Cars: ["Ford", "Fiat"],
  },
  {
    Name: "Tata Arena",
    Location: "Pune",
    Cars: ["Ford", "BMW"],
  },
  {
    Name: "Nexa Showroom",
    Location: "Noida",
    Cars: ["Suzuki", "Ford", "Tata", "Fiat"],
  },
];

const result = showrooms
  .filter((c) => {
     let existedInArray = true
     
     for(let i=0; i < filterArray.length; i  ){
      if(!c.Cars.includes(filterArray[i])) existedInArray = false
     }
     return existedInArray
  })
  .map((a) => a.Name);
  
 console.log(result) 

Ответ №4:

 const filterArray = ["Ford", "Fiat"];

const showrooms = [
  {
    Name: "Mark Auto",
    Location: "Delhi",
    Cars: ["Ford", "BMW", "Fiat"],
  },
  {
    Name: "Cardekho",
    Location: "Mumbai",
    Cars: ["Ford", "Fiat"],
  },
  {
    Name: "Tata Arena",
    Location: "Pune",
    Cars: ["Ford", "BMW"],
  },
  {
    Name: "Nexa Showroom",
    Location: "Noida",
    Cars: ["Suzuki", "Ford", "Tata", "Fiat"],
  },
];

const result = showrooms
  .filter((c) => {
     let existedInArray = true
     
     for(let i=0; i < filterArray.length; i  ){
      if(!c.Cars.includes(filterArray[i])) existedInArray = false
     }
     return existedInArray
  })
  .map((a) => a.Name);
  
 console.log(result)
 

Я думаю, что это сработает

Ответ №5:

Вы можете использовать reduce every, чтобы решить эту проблему за один цикл. Когда вы делаете что-то, объединяющее filter и map, reduce — действительно хороший способ.

 const filterArray = ['Ford', 'Fiat'];
const showrooms = [{
    "Name": "Mark Auto",
    "Location": "Delhi",
    "Cars": ['Ford', 'BMW', 'Fiat']
  },
  {
    "Name": "Cardekho",
    "Location": "Mumbai",
    "Cars": ['Ford', 'Fiat']
  },
  {
    "Name": "Tata Arena",
    "Location": "Pune",
    "Cars": ['Ford', 'BMW']
  },
  {
    "Name": "Nexa Showroom",
    "Location": "Noida",
    "Cars": ['Suzuki', 'Ford', 'Tata', 'Fiat']
  }
]


const result = showrooms.reduce((prev, curr) => {
  const isFilterCarsIncluded = filterArray.every(car => curr.Cars.includes(car));

  if (isFilterCarsIncluded) {
    return [...prev, curr.Name];
  }

  return prev;
}, []);

console.info(result); 

Ответ №6:

ДЕМОНСТРАЦИЯ:

 showrooms
  .filter(showroom => filterArray.every(item => showroom.Cars.includes(item)))
  .map(showroom => showroom.Name);
 

Выполнено.

Ответ №7:

с reduce помощью одной итерации мы можем накапливать желаемый результат

 const combine = (arr, filters) =>
  arr.reduce((acc, { Name, Cars }) => {
    filters.every((car) => Cars.includes(car)) amp;amp; acc.push(Name);
    return acc;
  }, []);

const filterArray = ["Ford", "Fiat"];

const showrooms = [
  {
    Name: "Mark Auto",
    Location: "Delhi",
    Cars: ["Ford", "BMW", "Fiat"],
  },
  {
    Name: "Cardekho",
    Location: "Mumbai",
    Cars: ["Ford", "Fiat"],
  },
  {
    Name: "Tata Arena",
    Location: "Pune",
    Cars: ["Ford", "BMW"],
  },
  {
    Name: "Nexa Showroom",
    Location: "Noida",
    Cars: ["Suzuki", "Ford", "Tata", "Fiat"],
  },
];

console.log(combine(showrooms, filterArray));