Search code examples
javascriptarrayssplice

How to Splice specific Letter From Arrays Javascript?


Is there a way to remove a specific character from arrays using the splice method? or any other method for that matter. I want to remove the letter 'W' that is attached to the numbers below. Thanks for your time! The best I could get was removing the entire part i.e "9W" rather than just having "9" left

   const sales = filteredProducts.map(function(product) {
    return {
        lastSaleSize: product.market.lastSaleSize,
        lastSale: product.market.lastSale,

      }
})
console.log(sales)

const newArr = sales.map((prev) => {
  const {
    lastSaleSize
  } = prev;
  const newLastSaleSize = lastSaleSize.match(/(.+?)W/, 'g')[1];
  const newElement = { ...prev,
    lastSaleSize: newLastSaleSize
  };
  return newElement;
});

console.log(newArr);



sales = 
0: {lastSaleSize: "9W", lastSale: 185}
1: {lastSaleSize: "8.5W", lastSale: 190}
2: {lastSaleSize: "11W", lastSale: 182}
3: {lastSaleSize: "9.5W", lastSale: 170}
4: {lastSaleSize: "9W", lastSale: 185}
5: {lastSaleSize: "7W", lastSale: 185}
6: {lastSaleSize: "8W", lastSale: 174}

Solution

  • What you're after is the map function, which iterates an array and returns a new (calculated) value in place of each of the original array's elements:

    const arr = [
      {lastSaleSize: "9W", lastSale: 172},
      {lastSaleSize: "8.5W", lastSale: 190},
      {lastSaleSize: "11W", lastSale: 182},
      {lastSaleSize: "9.5W", lastSale: 170},
      {lastSaleSize: "7W", lastSale: 185},
      {lastSaleSize: "8W", lastSale: 174},
      {lastSaleSize: "10W", lastSale: 189},
      {lastSaleSize: "12W", lastSale: 185},
    ];
    
    // You can use other methods, obviously
    function removeW(string) {
      return string.match(/(.+?)W/)[1];
    }
    
    const newArr = arr.map((prevElement) => {
      const { lastSaleSize } = prevElement; // Get the lastSaleSize value for the current element
      const newLastSaleSize = removeW(lastSaleSize);
      
      // Now generate the new Element, without the 'W'
      const newElement = {
        ...prevElement,
        lastSaleSize: newLastSaleSize,
      };
      return newElement;
    });
    
    console.log(newArr);