1

I have no idea to create array by json data

my code

for (let y of x.FACET){
    console.log(y["@KEY"])
    var numericArray: number[] = [y["@KEY"]];
    console.log(numericArray)
}

output

console.log(y["@KEY"]) show  
    1221 
    1334 
    1456 
    1876

console.log(numericArray) show
    ["1221"]
    ["1334"]
    ["1456"]
    ["1876"]

I want create [1221, 1334, 1456, 1876]; for sort number...

my listpage

<ion-list>
        <ion-item *ngFor="let item of  totalfilter">
          <p>{{item["@KEY"]}}</p>
        </ion-item>

        </ion-list>
4
  • 1
    before loop: var results = []; in loop: results.push(y["@KEY"]); Commented Mar 16, 2017 at 15:00
  • thanks for your help But I get error Cannot read property 'length' of undefined Commented Mar 16, 2017 at 15:07
  • Sorry, wasn't paying enough attention, my suggestion is javascript only. The posted answer is the same logic I was going for Commented Mar 16, 2017 at 15:11
  • Ahh , I'm sorry it's my mistake. your code is correct! thanks!!! Commented Mar 16, 2017 at 15:16

1 Answer 1

2

You have to initialise the array first, and after that push the values in there

let numericArray: number[] = [];

for (let y of x.FACET){
    numericArray.push(y["@KEY"]));       
}

One line solution:

let numericArray: number[] = x.FACET.map(v => parseInt(v["@KEY"]));

To sort the x.FACET array you can do this:

x.FACET.sort((a: any, b: any) => {
    return parseInt(a["@KEY"]) - parseInt(b["@KEY"]);
});
Sign up to request clarification or add additional context in comments.

1 Comment

I have one question , Can sort number by y["@KEY"] without create array? because I create array to sort number but list is not show by sort /// I editted post. please help me T-T

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.