查找数组中的对象中某个值最后一次出现位置并替换其值

新手上路,请多包涵
arr = [
{id: 1, common: 'first'},
{id: 2, common: 'middle'},
{id: 3, common: 'middle'}
]

把最后一个common的middle替换为last,用js要怎么弄

阅读 4k
3 个回答

简单理解了一下楼主的需求,供参考

const replaceLastRepeat = (
  arr: any[],
  replaces: Array<[string, string]>
) => {
  const obj: Record<string, any> = {};
  for (const item of arr) {
    obj[item.common] = {
      item,
      n: obj[item.common]?.n ? obj[item.common].n + 1 : 1
    };
  }
  for (const [k, v] of replaces) {
    obj[k].n > 1 && (obj[k].item.common = v);
  }
};
const arr = [
  { id: 1, common: 'first' },
  { id: 1, common: 'first' },
  { id: 2, common: 'middle' },
  { id: 3, common: 'middle' },
  { id: 4, common: 'middle' }
];
replaceLastRepeat(arr, [
  ['middle', 'last'],
  ['first', 'first2']
]);
console.log('after-arr :>> ', arr);

用 Lodash 的 findLast 或者 findLastIndex 都可以

import _ from "lodash";

const arr = [
    { id: 1, common: "first" },
    { id: 2, common: "middle" },
    { id: 3, common: "middle" }
];

const found = _.findLast(arr, it => it.common === "middle");
if (found) {
    found.common = "last";
}

console.log(arr);

如果不想用 Lodash,自己写一个也容易,逆向循环查找就行

Array.prototype.findLast = function (predicate) {
    for (let i = this.length - 1; i >= 0; i--) {
        if (predicate(this[i])) {
            return this[i];
        }
    }
};

const found = arr.findLast(it => it.common === "middle");
if (found) { found.common = "last"; }
console.log(arr);

如果想判断是否是重复的项,可以进行正向查找和反向查找,看得到的 index 是否相同。

function set(arr, key, value) {
    for (var i = arr.length; i--;) {
        if (arr[i].hasOwnProperty(key)) {
            arr[i][key] = value;
            return i;
        }
    }
    return -1;
}
console.dir(set(arr, "common", "last"));
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题