简体   繁体   English

如何从具有特定字符串匹配的数组中删除项目

[英]How to Delete an item from an array with specific string matching

I want to be able to match a specific string (full match not partial match) and then delete that specific item from the array if it matches.我希望能够匹配一个特定的字符串(完全匹配而不是部分匹配),然后在匹配时从数组中删除该特定项目。

I have some code but it doesn't seem to be deleting the item from the array.我有一些代码,但它似乎并没有从数组中删除该项目。 I do wish for it to change the original array and not create a new array so I am not using filter.我确实希望它更改原始数组而不是创建新数组,所以我没有使用过滤器。

How can I go about accomplishing this?我怎样才能 go 完成这个?

Current Code:当前代码:

 let recentSearches = [ { name: "Chicago, IL" }, { name: "Orlando, FL" }, { name: "Dallas, TX" } ]; let stringToRemove = "Dallas, TX"; recentSearches.some(recent => { if (recent.name === stringToRemove) { const index = recentSearches.indexOf(stringToRemove); if (index.== -1) { //Never goes into this if recentSearches,splice(index; 1). console;log(recentSearches); } } }). console;log(recentSearches);

JS Fiddle: enter link description here JS Fiddle:在此处输入链接描述

If you don't mind the output being a different array, use filter :如果您不介意输出是不同的数组,请使用filter

const filteredSearches = recentSearches.filter((recent) => recent.name !== stringToRemove);

If you need to modify the array in-place, you should visit the elements in reverse order (in case of multiple matches, which causes indices to shift) like so:如果您需要就地修改数组,您应该以相反的顺序访问元素(在多个匹配的情况下,这会导致索引移动),如下所示:

for (let i = recentSearches.length-1; i >= 0; i--) {
  if (recentSearches[i].name === stringToRemove) {
    recentSearches.splice(i, 1);
  }
}

The problem with your code is you use recentSearches.indexOf , but recentSearches isn't an array of strings, so nothing matches.您的代码的问题是您使用了recentSearches.indexOf ,但recentSearches不是字符串数组,因此没有任何匹配项。 You could modify your code as follows, but it won't work correctly in case of multiple mathces:您可以按如下方式修改您的代码,但在多个数学运算的情况下它将无法正常工作:

recentSearches.forEach((recent, index) => {
  if (recent.name === stringToRemove) {
    recentSearches.splice(index, 1);
  }
});

Alternatively, you could use findIndex (as suggested in other comments and answers) as follows:或者,您可以使用findIndex (如其他评论和答案中所建议),如下所示:

let index;
while (0 <= (index = recentSearches.findIndex((recent) => recent.name === stringToRemove)) {
  recentSearches.splice(index, 1);
}

indexOf() is for finding exact matches. indexOf()用于查找完全匹配。 Since your array contains objects, they'll never be equal to stringToRemove .由于您的数组包含对象,因此它们永远不会等于stringToRemove

Use findIndex() to get the index of an array element using a function that an compare the name property.使用findIndex()使用比较name属性的函数获取数组元素的索引。

There's also no need for using some() .也不需要使用some()

 let recentSearches = [{ name: "Chicago, IL" }, { name: "Orlando, FL" }, { name: "Dallas, TX" } ]; let stringToRemove = "Dallas, TX"; const index = recentSearches.findIndex(({ name }) => name == stringToRemove); if (index !== -1) { //Never goes into this if recentSearches.splice(index, 1); } console.log(recentSearches);

The JSON search is done wrongly. JSON 搜索做错了。

I have added the perfect code to complete your requirement.我已经添加了完美的代码来完成您的要求。 Find all instances and delete them with a while loop.查找所有实例并使用 while 循环删除它们。 This will ensure duplicate search terms are also removed if any.这将确保也删除重复的搜索词(如果有)。

let recentSearches = [
    {name: "Chicago, IL"},
    {name: "Orlando, FL"},
    {name: "Dallas, TX"}
];
  
let stringToRemove = "Dallas, TX";

while (recentSearches.findIndex(search => search.name === stringToRemove) > -1) {
    const index = recentSearches.findIndex(search => search.name === stringToRemove);
    recentSearches.splice(index, 1);
}

console.log(recentSearches);

You can use findindex.您可以使用 findindex。 Store it in a variable.将其存储在变量中。 And use splice并使用拼接

Another version of the findIndex, instead of using while, you could use for, a slight advantage here is that the index is then locally scoped inside the the for, were with a while loop you have the extra scope of the index, you could close the the scope of a let by doing { let index; while() {..}} findIndex 的另一个版本,而不是使用 while,您可以使用 for,这里的一个小优势是索引然后在 for 内部局部范围内,如果有一个 while 循环,你有索引的额外范围,你可以关闭通过执行{ let index; while() {..}} let 的范围{ let index; while() {..}} but the for loop avoids that without using {} . { let index; while() {..}}但 for 循环在不使用{}情况下避免了这种情况。

 let recentSearches = [ {name: "Chicago, IL"}, {name: "Orlando, FL"}, {name: "Dallas, TX"} ]; let stringToRemove = "Dallas, TX"; for (let index; index = recentSearches.findIndex( search => search.name === stringToRemove), index > -1;) recentSearches.splice(index, 1); console.log(recentSearches);

You can use this code:您可以使用此代码:

Array.prototype._arraycopy =  function(src, srcPos, dest, destPos, length) {
  while ((--length) >= 0) {
    dest[destPos++] = src[srcPos++];
  }
};

Array.prototype._fastRemove = function(es, i) {
  let newSize;
  if ((newSize = this.length - 1) > i) 
    this._arraycopy(es, i + 1, es, i, newSize - i);
  es[this.length = newSize] = null;
  this.length = newSize;
}

Array.prototype.__removeAt = function(index) {
  // Objects.checkIndex(index, size);
    const es = this;

    const oldValue =es[index];
    this._fastRemove(es, index);
    return oldValue;
}

Array.prototype.__removeAtValue = function(o) {
  const es = this;
  const size = this.size;
  let i = 0;
  (function() {
    if (o == null) {
        for (; i < size; i++)
            if (es[i] == null)
                return true;
    } else {
        for (; i < size; i++)
            if (Object.is(o, es[i]))
                return true;
    }
    return false;
  })()
  this._fastRemove(es, i);
  return true;
}

Array.prototype.remove = function(index) {
  return this.__removeAt(index)

}

Array.prototype.removeObj = function(obj) {
  return this.__removeAtValue(obj);
}

const arr = [1, 3, 4, 5, 10];
console.log(arr);
const rem = arr.remove(1)
console.log({ arr, rem });

const objs = [{ id: 1, name: "Hello" }, { id: 2, name: "Arrow" }, { id: 3, name: "Star" }]
console.log(objs);
const deleted = objs.removeObj({ id: 2, name: "Arrow" });
console.log({ objs, deleted })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM