Javascript – Algorithm (2)

Algorithm

How to replace text inside a string?

 var str = 'a b c';
 var replaced = str.split(' ').join('+');

How to merge 2 objects?

const response = {
  lat: -51.3303,
  lng: 0.39440
}

const item = {
  id: 'qwenhee-9763ae-lenfya',
  address: '14-22 Elder St, London, E1 6BT, UK'
}

const newItem = Object.assign({}, item, { location: response });

How to update value of a specific field?

let players = {
  abcdef: true,
  ghijkl: true,   // I want to change to 'ghijkl: false'
  mnopqr: true
}

const keys = Object.keys(players)
let players = ...(keys.reduce((carry, key) => {
  if ('ghijkl' !== key) {
    carry[key] = state.players[key]
  }
  return carry
}, {})),  
/* {
  abcdef: true,
  mnopqr: true
}*/

players = {
  ...players,
  ghijkl: false
}

How to remove duplicates from array of objects?

var test = [
{id:1, PlaceRef: "*00011", Component: "BATH", SubLocCode: "BAT", BarCode: ""},
{id:2, PlaceRef: "*00022", Component: "BAXI10R", SubLocCode: "KIT", BarCode:""},
{id:1, PlaceRef: "*00011", Component: "BATH", SubLocCode: "BAT", BarCode: ""},
{id:3, PlaceRef: "*00011", Component: "ANR190", SubLocCode: "B1", BarCode: ""}]

// Create Set of unique items
var arrUniqId = [...new Set(test.map(({id}) => id))]  // 1, 2, 3
var uniq = arrUniqId.map(e => test.find(({id}) => id == e));

console.log(uniq)

How to merge 2 arrays without duplicated items?

For example, merge following 2 arrays without duplicated ID

var arrayOne = [
    {
        'ID': 1,
        'FirstName': 'Sally'
    },
    {
        'ID': 2,
        'FirstName': 'Jim'
    },
    {
        'ID': 3,
        'FirstName': 'Bob'
    }
];

var arrayTwo = [
    {
        'ID': 2,
        'FirstName': 'Jim'
    },
    {
        'ID': 4,
        'FirstName': 'Tom'
    },
    {
        'ID': 5,
        'FirstName': 'George'
    }
];

Solution

Create a Set of ID first

var ids = new Set(arrayOne.map(d => d.ID));

Then merge 2 arrays and check duplicated ID

var mergedArray = [...arrayOne, ...arrayTwo.filter(d => !ids.has(d.ID))];

How to filter an array by another array?

const dataArray = [
    {
        id: 1,
        value: 'hi'
    },
    {
        id: 2,
        value: 'hii'
    },
    {
        id: 3,
        value: 'hiii'
    },
    {
        id: 4,
        value: 'hiiii'
    },
]

const filterArray = [1, 4]

const filterResult = [
    {
        id: 1,
        value: 'hi'
    },
    {
        id: 4,
        value: 'hiiii'
    },
]

Solution

const filterResult = dataArray.filter((item) => {
    const id = item.id   // 1, 2, 3, 4
    return filterArray.indexOf(id) >= 0  // "this" is "filterArray"
})

How to convert data by reduce?

// Convert array to object
const obj = arrData.reduce((objNewData, element) => {

    if (!objNewData[element.ACertainProperty]) {
        objNewData[element.ACertainProperty] = []
    }

    objNewData[element.ACertainProperty].push(element)

    return objNewData
}, {})

/* arrData = [
  {
    name: 'aaaa',
    age: 18
  },
  {
    name: 'aaaa',
    age: 20
  },
  {
    name: 'bbbb',
    age: 16
  },
]

obj = {
  'aaaa': [
    {
      name: 'aaaa',
      age: 18
    },
    {
      name: 'aaaa',
      age: 20
    },
  ],
  'bbbb': [
    {
      name: 'bbbb',
      age: 16
    }
  ]
}
*/

How to convert object to array?

TRANSFER

{
    "teacher_1": [
        {
            name: 'AAAA',
            class: '10A1'
        },
        {
            name: 'BBBB',
            class: '10A2'
        },
        {
            name: 'CCCC',
            class: '10A3'
        },
    ],
    "teacher_2": [
        {
            name: 'DDDD',
            class: '10A4'
        },
        {
            name: 'BBBB',
            class: '10A2'
        },
        {
            name: 'CCCC',
            class: '10A3'
        },
    ],
}

TO

[
    {
        name: 'AAAA',
        class: '10A1'
        teacher: ["teacher_1"]
    },
    {
        name: 'BBBB',
        class: '10A2'
        teacher: ["teacher_1", "teacher_2"]
    },
    {
        name: 'CCCC',
        class: '10A3'
        teacher: ["teacher_1", "teacher_2"]
    },
    {
        name: 'DDDD',
        class: '10A4'
        teacher: ["teacher_2"]
    }
]

How to get value of a property from an array of object?

Be the first to comment

Leave a Reply

Your email address will not be published.


*