Javascript

Manipulasi Array di Javascript Dengan Paradigma Functional Programming

Akhir-akhir ini sering berurusan dengan javascript dan kebetulan belajar paradigma baru yang selama ini hampir tidak pernah dipake, yaitu functional programming atau biasa disingkat FP.

Salah satu konsep paling umum di FP adalah menghindari proses mutate atau melakukan perubahan state dari suatu data (immutable)

Contoh proses mutate adalah seperti berikut.

let names = ['alex', 'mike', 'carl', 'james']
console.log(names)
names.push('adam') // proses mutate
console.log(names)

Bisa dilihat contoh di atas bahwa terjadi perubahan state dari variable “names”, dimana semula berisi 4 item kemudian terjadi manipulasi state sehingga menjadi 5 item.

Sebagai dokumentasi pembelajaran saya, maka akan saya catat pada blog ini beberapa cara manipulasi array menggunakan paradigma FP dengan bantun fungsi spread pada javascript.

Add item baru pada array.

// Sebagai contoh kita ingin menambahkan `adam` ke dalam array.
let names = ['alex', 'mike', 'carl', 'james']
let newNames = [
  ...names,
  'adam'
]

Delete item pada array.

// Sebagai contoh kita ingin menghapus carl dari array.
// Ada 2 cara dengan cara filter dan menggunakan spread.
let names = ['alex', 'mike', 'carl', 'james']
let index = names.findIndex(item => item === 'carl')

let namesMethod1 = names.filter(item => item !== 'carl')
let namesMethod2 = [
...names.slice(0, index),
...names.slice(index + 1),
]

Edit item pada array.

// Sebagai contoh dengan data structure yang lebih komplex, kita ingin
// melakukan perubahan status pada order004 menjadi paid.
let orders = [
  {id: 'order001', status: 'unpaid'},
  {id: 'order002', status: 'unpaid'},
  {id: 'order003', status: 'unpaid'},
  {id: 'order004', status: 'unpaid'},
  {id: 'order005', status: 'unpaid'},
  {id: 'order006', status: 'unpaid'},
]
let index = orders.findIndex(order => order.id === 'order004')

let newOrders = [
  ...orders.slice(0, index),
  {
    ...orders[index],
    status: 'paid',
  },
  ...orders.slice(index + 1)
]

Contoh diatas adalah hal yang umum dalam manipulasi array di javascript, semoga bisa bermanfaat bagi pembaca.

Referensi:
https://jaketrent.com/post/remove-array-element-without-mutating/
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

 

Fix NVM Keeps Forgeting Node Version in New Terminal Session on OSX

I’m installing NVM on OSX but apparently NVM not saving my config, so after installing latest version of node.js and switch to it in new terminal session or after restarting the system, NVM still using old version of node.js.

And follow this link to fix this issue. 😀

Change Vue.js Default Template Tags

As a Django developer I get used to use tag “{{” and “}}” in my template, but when I’m trying to use Vue.js in my project I have to change Vue’s default tags, because Django template and Vue.js has the same tags “{{” and “}}” for binding variable data in html template.

Here is how to change default Vue.js tags

Vue.config.delimiters = ["[[", "]]"];

Now you can using “[[” and “]]” as your Vue.js tags in your project.
FYI you can replace with wathever you want for Vue tags delimiter, but I get used to use double square braces. 😀

Reference: http://stackoverflow.com/a/33628663/1936697

Get Particular Object Property Within Javascript Array

I have some object within javascript array and I need to get all data only the name or whatever property inside the object. Usually I iterate entire array and append selected property into new empty array. Below is the code example.

var myList = [{name: 'foo', age: 21}, {name: 'bar', age: 15}, {name: 'john', age: 29}]
var listName = [];
for (var i = 0; i < myList.length; i++) {
    listName.push(myList[i].name);
}
console.log(listName); // [ 'foo', 'bar', 'john' ]

And code below is the alternative using map.

var myList = [{name: 'foo', age: 21}, {name: 'bar', age: 15}, {name: 'john', age: 29}];
var listName = myList.map(function(data){
    return data.name;
});
console.log(listName); // // [ 'foo', 'bar', 'john' ]

Reference: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/map

Sum Array of Integer in Javascript with Reduce

Alternative code to sum up list of integer in Javascript.

var totalArray = [1, 3, 5].reduce(function(prev, current) {
    return prev + current;
});
console.log(totalArray); // 9

Code above equivalent with.

var arrayNumber = [1, 3, 5];
var totalArray = 0;
for (var i = 0; i < arrayNumber.length; i++) {
    totalArray += arrayNumber[i];
}
console.log(totalArray); // 9

I don’t know about performance comparison, soo let you test then and quite similar with python reduce, eh? 😀

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

Merge 2 or More Array in Javascript

Here is code snippet to merge 2 or more array in javascript.

var arr1 = ["A", "B", "Z"];
var arr2 = ["X"];
var arr3 = [10];

var mergedArray = arr1.concat(arr2).concat(arr3);
console.log(mergedArray); // ["A", "B", "C", "X", 10]

Reference: http://stackoverflow.com/a/1584377/1936697