Home > Net >  How to copy one element of an array to another array in javascript?
How to copy one element of an array to another array in javascript?

Time:09-02

I have an array of objects and I want to copy some of its elements into another array, how can I do it?

Let's say:

    original = [{name: "a", age: 20},                
                {name: "b", age: 25},
                {name: "c", age: 30}
               ];

    var k = 0;
    for(var i = 0; i < original.lenght; i  )
      if(original[i].age > 22){
        selected[k] = original[i]; ===> needs to change.
        k  ;
      }

CodePudding user response:

You can just use filter: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter.

const selected = original.filter(person => person.age > 22)

CodePudding user response:

You can use filter to create a new array with anything matching your if statement.

let original = [{name: "a", age: 20},                
                {name: "b", age: 25},
                {name: "c", age: 30}
               ];
let min_age = 23;
let selected2 = original.filter((element) => element.age > min_age);
console.log(selected2)
Or if selected already exists as an array and you want to append to it, you can just use push.

let original = [{
    name: "a",
    age: 20
  },
  {
    name: "b",
    age: 25
  },
  {
    name: "c",
    age: 30
  }
];
let min_age = 23;
let selected = [];


original.forEach(function(e) {
  if (e.age > min_age) {
    selected.push(e)
  }
});

console.log(selected)

  • Related