Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
96 views
in Technique[技术] by (71.8m points)

javascript - Combine two arrays to filter a common result?

I have two arrays - the actual array has 2500 entries, now showing few for sample ). I have implemented a realtime search functionality in react native. This is my function,

By this, when user types anything it filters and displays in flatlist ! It works perfectly, but the thing is i have another array2 in which it has alias name for the cities in array1 ( note: not every cities have alias names ). My question is how to combine both to filter,

For example : when user types "Tiruchirapalli" or "Trichy" it should show alias name and for the cities which doesn't have alias its original name should be shown !

How to achieve this ?

Array1

const array1 = [{
    "id": "117",
    "name": "Tiruchirapalli",
    "stateId": "101"
  },
  {
    "id": "27110",
    "name": "Ganoda",
    "stateId": "1405"
  },
  {
    "id": "203",
    "name": "Tenkasi",
    "stateId": "101"
  },
  {
    "id": "115",
    "name": "Thanjavur",
    "stateId": "101"
  },
];

Array2

const array2 = [{
    "id": 1850,
    "cityName": "Tenkasi",
    "aliasNames": [
      "Thenkasi"
    ]
  },
  {
    "id": 4521,
    "cityName": "Tiruchirapalli",
    "aliasNames": [
      "Trichy"
    ]
  },
  {
    "id": 115,
    "cityName": "Thanjavur",
    "aliasNames": [
      "Tanjore"
    ]
  },
];

Attempt

searchFilterFunction = text => {
  this.setState({
    typedText: text
  });
  const newData = this.arrayholder.filter(item => {
    const itemData = `${item.name.toUpperCase()}`;
    const textData = text.toUpperCase();
    return itemData.indexOf(textData) > -1;
  });
  this.setState({
    data: newData
  });
};
question from:https://stackoverflow.com/questions/65940589/combine-two-arrays-to-filter-a-common-result

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Just an example, I think you're on the right track. I didn't define otherIndex but I think you get the idea:

searchFilterFunction = text => {
  this.setState({
    typedText: text
  });
  const newData = this.arrayholder.filter(item => {
    const itemData = `${item.name.toUpperCase()}`;
    const textData = text.toUpperCase();
    const index = itemData.indexOf(textData) > -1
    return index ? array2[index] : array1[otherIndex]
  });
  this.setState({
    data: newData
  });
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...