Alphabetize items in a JavaScript object? - javascript

Say I have an object that looks like this:
countrylist:{
regions:[
{
region: "Europe",
countries: [
{
"country":"Albania",
"href":"eu",
"locale":"en_al"
},
{
"country":"France",
"href":"eu",
"locale":"en_fr"
},
{
"country":"Ireland",
"href":"eu",
"locale":"en_ie"
}]
},
region: "Asia",
countries: [
{
"country":"China",
"href":"as",
"locale":"ch"
},
{
"country":"Japan",
"href":"as",
"locale":"jp"
},
{
"country":"Thailand",
"href":"as",
"locale":"th"
}]
}
]}
If you could see the whole object, you would see that it's grouped by region, and the countries within each region are sorted alphabetically. However, I need to populate a dropdown menu of all the countries, alphabetized, but not by region. What's the cleanest method to go about sorting these items?
I originally pushed the country field to an empty array and sorted that. However, I need to preserve the relationship between the country field and its corresponding href and locale fields.

Initialize an empty array, then go through the regions and append all the countries to that array. When you're done, sort the array.
var countries = [];
for(var i = 0; i < countrylist.regions.length; i++)
Array.prototype.push.apply(countries, countrylist.regions[i].countries);
countries.sort(function(a, b) {
return a.country > b.country;
});
console.log(countries);
http://jsfiddle.net/Jehsb/

You need to walk your structure and create an array of country names. You can then sort the array, and you're done.
var arr = [];
for(var i = 0; i < countryList.regions.length; i++){
var countries = countryList.regions[i].countries;
for(var j = 0; j < countries.length; j++){
arr.push(countries[j].country);
}
}
arr.sort();
If you need the other information as well, what you'd need is a flat array of all country objects, and then apply a custom sort function:
var arr = [];
for(var i = 0; i < countryList.regions.length; i++){
var countries = countryList.regions[i].countries;
for(var j = 0; j < countries.length; j++){
arr.push(countries[j]);
}
}
arr.sort(function(xx,yy){
return xx.country < yy.country ? -1 : 1;
});

Related

Need to iterate through arrays having objects Vue

I have an array list and each list are groups of objects. I need to iterate through each group and check if an object in a list satisfies a condition.
This is what have been able to do but, doesn't iterate through each object.
for (i = 1; i <= this.portfolioDetails.length; i++) {
for (var j = 1; j < this.portfolioDetails[i].length; j++)
{
console.log(portfolioDetails[i][j]);
}
}
This is the list of array objects:
portfolioDetails:Array[3]
0:Object
ACCOUNTID:"S1001"
ACCOUNTNAME:"Bla bla bla"
ACCRUEDINTERESTALL:0
PRICE:0.69
UNITS:60.49
VALUE:41.98
product:null
1:Object
ACCOUNTID:"S1002"
ACCOUNTNAME:"blo bla blo"
ACCRUEDINTERESTALL:0
PRICE:0.69
UNITS:60.49
VALUE:41.98
product:null
2:Object
ACCOUNTID:"S1003"
ACCOUNTNAME:"blik blik blik"
ACCRUEDINTERESTALL:0
PRICE:0.69
UNITS:60.49
VALUE:41.98
product:null
This is simple JavaScript and has nothing to do with VueJS per se. The reason your iteration is not working is because you start with i = 1 while in coding you start with an index of 0. Also, you are including the last number with your comparison statement <= which is not in the array (because you start counting at 0, not at 1). On top of that, you can just print out object values by their keys. This all adds up to something like this:
for (let i = 0; i < this.portfolioDetails.length; i++) {
console.log(this.portfolioDetails[i].ACCOUNTID)
}
Your top loop iterate should look like:
for (i = 0; i < this.portfolioDetails.length; i++) { ... }
This code should work:
for (let i = 0; i < this.portfolioDetails.length; i--) {
for (let j = 0; j < this.portfolioDetails[i].length; j--)
{
// Check conditions here
if (this.portfoiloDetails[i][j].ACCOUNTID === 'S1002') {
// Actions goes here
}
}
}
Hi the given list of array objects is unclear but if you are trying to iterate over JSON data type, you can use the code below. This code dynamically discovers the properties and return the value of each property.
<script>
var portfolioDetails = { 'data': [
{ 'fname': 'joe', 'lname': 'smith', 'number': '34'} ,
{ 'fname': 'jim', 'lname': 'Hoff', 'number': '12'} ,
{ 'fname': 'jack', 'lname': 'jones', 'number': '84'}
] };
//iterate over the records
for (i = 0; i < portfolioDetails["data"].length; i++) {
var data = this.portfolioDetails["data"][i];
var propertiesCount = Object.getOwnPropertyNames(data).length;
//iterate over the properties of each record
for (var j = 0; j < propertiesCount; j++)
{
var propName = Object.getOwnPropertyNames (data)[j];
console.log(portfolioDetails["data"][i][propName]);
}
}
</script>

Checking to see if key-value has the same value

So I'm turning a .csv file into an array of key-value pairs, I'm trying to print each unique value and i'm trying to figure out how I can check to make sure the values aren't identical. So for example:
var data = $.csv.toObjects(csv);
will turn everything into
[
{heading1:"value1_1",heading2:"value2_1",heading3:"value3_1",heading4:"value4_1",heading5:"value5_1"}
{heading1:"value1_2",heading2:"value2_2",heading3:"value3_2",heading4:"value4_2",heading5:"value5_2" }
]
I want to check if heading1 has the same value in both instances and if it does to only print the first instance of that value.
Convert your data into key–value pairs, where keys are the values from "heading1" like so:
var data = [
{heading1:"value1_1",heading2:"value2_1",heading3:"value3_1",heading4:"value4_1",heading5:"value5_1"},
{heading1:"value1_2",heading2:"value2_2",heading3:"value3_2",heading4:"value4_2",heading5:"value5_2" },
];
var filtered = {};
for (var i = 0, max = data.length; i < max; i++) {
var record = data[i];
if (!filtered[record.heading1]) {
filtered[record.heading1] = {};
}
filtered[record.heading1] = record;
}
var keys = Object.keys(filtered);
for (var i = 0, max = keys.length; i < max; i++) {
console.log(filtered[keys[i]]); // do print
}

How to use a key array to remove specific items from a main array?

First of all thank you to whoever reads this whole question. I am having trouble writing a function that can take a key array and use the indices to remove like items from a main array.
My main Array
var mainArray = [
{fruit:"apple",color:"red"},
{fruit:"orange",color:"orange"},
{fruit:"banana",color:"yellow"},
{fruit:"apple",color:"red"},
{fruit:"banana",color:"yellow"},
{fruit:"mango",color:"greenishyellowishred"}
]
Array of items will be added to this mainArray and I need to remove multiple items at a time.
My key Array
var keyArray = [{fruit:"apple",color:"red"}, {fruit:"banana",color:"yellow"}]
I am attempting to remove the "apple" and the "banana" by using a for loop to decrement through the array to maintain the integrity of the mainArray.
for(var i = mainArray.length - 1; i > -1; i--) {
for(var j = keyArray.length - 1; j > -1; j--) {
if(mainArray[i].fruit === keyArray[j].fruit) {
mainArray.splice(i, 1)
keyArray.splice(j, 1)
}
}
}
My issue comes when I am trying to read mainArray[i].fruit if i = 0
Thanks in advance for any help possible.
Try the following way:
var mainArray = [
{fruit:"apple",color:"red"},
{fruit:"orange",color:"orange"},
{fruit:"banana",color:"yellow"},
{fruit:"apple",color:"red"},
{fruit:"banana",color:"yellow"},
{fruit:"mango",color:"greenishyellowishred"}
];
var keyArray = [{fruit:"apple",color:"red"}, {fruit:"banana",color:"yellow"}];
var tempArray = [];
for(let j = 0; j < keyArray.length; j++) {
for(let i = 0; i < mainArray.length; i++) {
if(mainArray[i].fruit === keyArray[j].fruit) {
tempArray.push(mainArray[i]);
}
}
}
mainArray = mainArray.filter( function( el ) {
return !tempArray.includes( el );
});
console.log(mainArray);

Angular filter that compares an array of strings in ng-repeating objects - with an array of strings, and filters out objects that do not match

This Angular filter is being passed an array of objects used in an ng-repeat (item in items).
[{
title: "Star Wars",
categories: ["Adventure", "Family"]
}, {
title: "Star Search",
categories: ["Realty", "Fantasy"]
}, {
title: "Star Trek",
categories: ["Sci-Fi", "Fantasy"]
}]
And an array of strings (categoriesFiltered)
["Adventure", "Sci-Fi"]
What would be the best way to iterate through the items in the ng-repeat and compare the categories array... to the categoriesFiltered array, and push the items that match to the new filtered array?
This is how far I have come
categoryFilter.filter('filterCategories', function () {
return function (items, categoriesFiltered) {
var filtered = [];
for (var i = 0; i < items.length; i++) {
for (var j = 0; j < items[i].categories; j++) {
if (filtered.indexOf(items[i].categories[j]) === -1) {
filtered.push(items[i]);
};
};
};
return filtered;
};
});
Here is a plunker...
There are a few problems.
Your returned filtered array falls outside the returned function, it should be inside.
You're not checking for items[i].categories.length in your for loop condition.
You're using the wrong array to check the indexOf.
I'm assuming your categoriesFiltered example was a typo looks like ["Adventure", "Sci-Fi"] because [{"Adventure", "Sci-Fi"}] is invalid javascript.
Try this:
categoryFilter.filter('filterCategories', function () {
return function (items, categoriesFiltered) {
var filtered = [];
for (var i = 0; i < items.length; i++) {
for (var j = 0; j < items[i].categories.length; j++) {
if (categoriesFiltered.indexOf(items[i].categories[j]) > -1) {
filtered.push(items[i]);
}
}
}
return filtered;
};
});

Removing Duplicates in Javascript 2D Array

I have already first column sorted 2D Javascript Array
var arr = [[12.485019620906078, 236.90974767017053|166.7059999999991|244.15878139435978|156.54100000000025],
[12.735148445872, 238.038907254076|203.3000000000006|245.7107245706185|213.46500000000034],
[47.15778769718685, 238.038907254076|203.3000000000006|244.15878139435978|156.54100000000025],
[47.580051233708595, 236.90974767017053|166.7059999999991|245.7107245706185|213.46500000000034]
];
I am trying to remove the duplicates based on the last two values in the [i][1] part of array
244.15878139435978|156.54100000000025
245.7107245706185|213.46500000000034
using following function which is not giving correct output
function remDupes(arr)
{
for(var i=0; i<arr.length-1; i++)
{
var i1 = arr[i][1].split("|");
var item1 = i1[2]+"|"+i1[3];
for(var j=i+1; j<arr.length; j++)
{
var i2 = arr[j][1].split("|");
var item2 = i2[2]+"|"+i2[3];
if(item1 == item2)
{
arr.splice(j,1);
}
}
}
return arr;
}
I am looking for final array like this.
[
[12.485019620906078, 236.90974767017053|166.7059999999991|244.15878139435978|156.54100000000025],
[12.735148445872, 238.038907254076|203.3000000000006|245.7107245706185|213.46500000000034]
]

Categories

Resources