How do I group forEach results without a key in javascript?

Viewed 67

I have a list of url's in WordPress that needs to be sorted in an efficient way through loop.

var urlList = [
  {
    "URL": "https://example.com/cat1/aa/bb/cc",
    "Last crawled": "Jun 23, 2019"
  },
  {
    "URL": "https://example.com/cat2/aa",
    "Last crawled": "Jun 23, 2019"
  },
  {
    "URL": "https://example.com/cat1/aa/bb/cc/dd/ee",
    "Last crawled": "Jun 23, 2019"
  },
  {
    "URL": "https://example.com/cat3/aa/bb/cc/",
    "Last crawled": "Jun 23, 2019"
  },
  {
    "URL": "https://example.com/cat2/aa/bb",
    "Last crawled": "Jun 23, 2019"
  },
  {
    "URL": "https://example.com/cat1/aa/bb",
    "Last crawled": "Jun 23, 2019"
  }
]

urlList.forEach(function(item) {
    var myUrl = item.URL.split("/");
    console.log("https://example.com/" + myUrl[3]);
});

I tried to output the json object with forEach then split the url so I can get the second part of the url which is cat1, cat2, cat3. Each url has no definite length.

Do you know how can I achieve the output below? I am somehow aiming to do it inside the forEach loop.

https://example.com/cat1
https://example.com/cat1
https://example.com/cat1
https://example.com/cat2
https://example.com/cat2
https://example.com/cat3

Note: The categories is NOT limited to cat1,cat2,cat3. It could be also https://example.com/news or https://example.com/events

Any help is greatly appreciated. Thanks.

2 Answers

You could get the link with the first path and sort the array.

var urlList = [{ URL: "https://example.com/cat1/aa/bb/cc", "Last crawled": "Jun 23, 2019" }, { URL: "https://example.com/cat2/aa", "Last crawled": "Jun 23, 2019" }, { URL: "https://example.com/cat1/aa/bb/cc/dd/ee", "Last crawled": "Jun 23, 2019" }, { URL: "https://example.com/cat3/aa/bb/cc/", "Last crawled": "Jun 23, 2019" }, { URL: "https://example.com/cat2/aa/bb", "Last crawled": "Jun 23, 2019" }, { URL: "https://example.com/cat1/aa/bb", "Last crawled": "Jun 23, 2019" }],
    result = urlList
        .map(({ URL }) => URL.match(/^https:\/\/example.com\/[^\/]+(?=\/)/)[0])
        .sort((a, b) => a.localeCompare(b));

console.log(result);

An example using underscore.js (you can chain calls with underscore I splitted for understanding purpose):

var s = _.map(urlList, function(i) {
  return i.URL.split("/")[3];
});
var sorted = _.sortBy(s)
var projection = _.map(sorted, function(p) {
  console.log("https://example.com/" + p);
});

Example in jsfiddle :

https://jsfiddle.net/1nwg9pq7/

Related