Home > Back-end >  Finding same array element in a different array and renaming it to be incremental
Finding same array element in a different array and renaming it to be incremental

Time:09-22

Finding same array element in another array and renaming it to be incremental. in the script below , i would like to increment the same element to 1 dynamically without manually putting in "motor" for it to be rename as "motor 1"

For an example , use case

//original array
["car","motor","bicycle","tricyle","motor"]

//result should be 
["car","motor","bicycle","tricyle","motor 1"]

This is the script i tried

let _temparr = ["car","motor","bicycle","tricyle","motor"]
let _newarr  = new Array();
let counter = 0;

for(let i = 0 ; i < _temparr.length;i  ){
  
  // Push _temparr element to _newarr
  for(let a = 0; a < _newarr.length; a  ){

    // if _newarr consist of motor , increment counter  1 and push as "Motor 1"
    if(_newarr[i] === "motor"){
      counter  
      _newarr.push(_temparr[i]   counter)
    }
  }
  _newarr.push(_temparr[i])

The logic i came out with is, i will loop _temparray and push it to a new arrau which is :_newarr , within the first loop of _newarr if it finds the same element in _temparray. counter will increment . but im nnot sure what is the best practice to do this. i found some topics on using const found = arr1.some(r=> arr2.includes(r)) but this will remove if it has the same element

CodePudding user response:

You can keep a counter for every word/element and use .map to create the new array, updating each element as needed:

const counter = new Map();
console.log(
  ["car","motor","bicycle","tricyle","motor"].map(
    element => {
      if (!counter.has(element)) {
        counter.set(element, 1);
        return element;
      }
      const count = counter.get(element);
      counter.set(element, count 1);
      return element   " "   count;
    }
  )
);

CodePudding user response:

Maybe you could consider using a Map:

const originalArray = ["car", "motor", "bicycle", "tricyle", "motor"];
const newArray = [];
const counter = new Map();
originalArray.forEach(item => {
  if (counter.has(item)) {
    newArray.push(`${item} ${counter.get(item)}`);
    counter.set(item, counter.get(item)   1);
  } else {
    newArray.push(item);
    counter.set(item, 1);
  }
});
console.log(newArray);

  • Related