-2

can someone help me with some code to splice an array and push to new array. I have an arrays

someArray = [{
  name: "Kristian",
  lines: "2,5,10"
}, {
  name: "John",
  lines: "1,19,26,96"
}, {
  name: "Kristian",
  lines: "2,58,160"
}, {
  name: "Felix",
  lines: "1,19,26,96"
}];

i want to splice where name = to Kristian and push to a new array

Mohammad Usman
  • 30,882
  • 16
  • 80
  • 78
jack
  • 17
  • 7

3 Answers3

1

You can use

Array.prototype.filter()

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

Array.prototype.splice()

The splice() method changes the contents of an array by removing existing elements and/or adding new elements.

var someArray = [{name:"Kristian", lines:"2,5,10"},{name:"John", lines:"1,19,26,96"},{name:"Kristian", lines:"2,58,160"},{name:"Felix", lines:"1,19,26,96"}];

var res = someArray.filter((p,i) => {
  if(p.name=="Kristian"){
    someArray.splice(i, 1); //remove the mached object from the original array
    return p;
  }
});

console.log(res);
console.log('----------------');
console.log(someArray);
Mamun
  • 58,653
  • 9
  • 33
  • 46
1

You can use .reduce() method along-with .splice():

let data = [
  {name:"Kristian", lines:"2,5,10"}, {name:"John", lines:"1,19,26,96"},
  {name:"Kristian", lines:"2,58,160"}, {name:"Felix", lines:"1,19,26,96"}
];
  
let result = data.reduce((r, c, i, a) => {
  if(c.name = 'Kristian')
    r.push(a.splice(i, 1));
  return r;
}, []);

console.log(result);
console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Mohammad Usman
  • 30,882
  • 16
  • 80
  • 78
0

You could use a mixture of filter and map:

const filtered = someArray.filter(obj => obj.name !== "Kristian")
const newArray = someArray.map(obj => obj.name === "Kristian")

Filtered will remove the items whilst map will create a new array with the removed items

Stretch0
  • 5,526
  • 3
  • 48
  • 93